background preloader

Ruby

Facebook Twitter

Rails

Yeld. Ruby.Metaprogramming. class_eval. Getting dimension of multidimensional array in ruby. Coralbook/ch3.html. Chapter 3Manipulating Structured Data Simple variables are not adequate for real-life programming. Every modern language supports more complex forms of structured data and also provides mechanisms for creating new abstract data types. Historically, arrays are the earliest known and most widespread of the complex data structures. Long ago, in FORTRAN, they were called subscripted variables; today they have changed somewhat, but the basic idea is the same in all languages. More recently, the hash has become an extremely popular programming tool. Like the array, it is an indexed collection of data items; unlike the array, it may be indexed by any arbitrary object.

Finally, we look at more advanced data structures. But let's not get ahead of ourselves. Note in the following example how a reference beyond the end of the array causes the array to grow. K = [2, 4, 6, 8, 10] k[1..2] = [3, 3, 3] # [2, 3, 3, 3, 8, 10] k[7] = 99 # [2, 3, 3, 3, 8, 10, nil, 99] if g ! Listing 3.1: Specialized Sorting. Floating point - Set the display precision of a float in Ruby. Ruby on rails - Determine if a string is a valid float value.

Exceptii

Ruby Exceptions. Raising An Exception An exception is a special kind of object, an instance of the class Exception or a descendant of that class that represents some kind of exceptional condition; it indicates that something has gone wrong. When this occurs, an exception is raised (or thrown). By default, Ruby programs terminate when an exception occurs. But it is possible to declare exception handlers. An exception handler is a block of code that is executed if an exception occurs during the execution of some other block of code. Raising an exception means stopping normal execution of the program and transferring the flow-of-control to the exception handling code where you either deal with the problem that's been encountered or exit the program completely.

Which of these happens - dealing with it or aborting the program - depends on whether you have provided a rescue clause (rescue is a fundamental part of the Ruby language). Reference: The above figure is from the Programming Ruby book. The output is: Ruby on Rails - Part 1: Hello World. Regexp. A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor.

Regular expressions (regexps) are patterns which describe the contents of a string. They’re used for testing whether a string contains a given pattern, or extracting the portions that match. They are created with the /pat/ and %r{pat} literals or the Regexp.new constructor. A regexp is usually delimited with forward slashes (/). /hay/ =~ 'haystack' /y/.match('haystack') If a string contains the pattern it is said to match. /needle/.match('haystack') /hay/.match('haystack') Specifically, /st/ requires that the string contains the letter s followed by the letter t, so it matches haystack, also. The following are metacharacters (, ), [, ], {, }, ., ? /1 \+ 2 = 3\? Patterns behave like double-quoted strings so can contain the same backslash escapes. /\s\u{6771 4eac 90fd}/.match("Go to 東京都") Character Classes¶ ↑ Repetition¶ ↑ /\$(? Rubular: a Ruby regular expression editor and tester.

Float (IEEE754 Single precision 32-bit) String (Ruby 2.0. Str % arg → new_str click to toggle source Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array or Hash containing the values to be substituted. See Kernel::sprintf for details of the format string. static VALUE rb_str_format_m(VALUE str, VALUE arg) { volatile VALUE tmp = rb_check_array_type(arg); if (! NIL_P(tmp)) { return rb_str_format(RARRAY_LENINT(tmp), RARRAY_PTR(tmp), str); } return rb_str_format(1, &arg, str); } str * integer → new_str click to toggle source Copy — Returns a new String containing integer copies of the receiver. integer must be greater than or equal to 0. "Ho! Str + other_str → new_str click to toggle source Concatenation—Returns a new String containing other_str concatenated to str. "Hello from " + self.to_s str << integer → str click to toggle source str << obj → str Append—Concatenates the given object to str.

In this example ... ascii_only? Beginning Programming with Ruby: Customized Sorting. Note! This whole page is an advanced topic. How Sorting Arrays Works Before we get into sorting arrays, let’s ask a fundamental question: How do you sort things? If you had a set of index cards with people’s last names on them, how would you sort them into alphabetical order? Ruby does something very similar. How Ruby Compares Things By default, Ruby’s sort algorithm always sorts into ascending order. Comparison operator on them. . -1 if a is less than b 0 if a is equal to b 1 if a is greater than b The sort operator will switch the positions of a and b if the comparison returns 1 (because that means the two items are not in the proper order). By the way: when Ruby uses the <=> operator on strings, it compares them in ASCII order (according to their computer encoding), so the comparison is case sensitive.

The question becomes: how can you sort an array in reverse order, or sort strings in a case-insensitive manner? Data.sort { |a, b| a <=> b } words.sort { |a, b| a.upcase <=> b.upcase } Arrays. You can create an array by listing some items within square brackets ([]) and separating them with commas. Ruby's arrays can accomodate diverse object types. ruby> ary = [1, 2, "3"] [1, 2, "3"] Arrays can be concatenated or repeated just as strings can. ruby> ary + ["foo", "bar"] [1, 2, "3", "foo", "bar"] ruby> ary * 2 [1, 2, "3", 1, 2, "3"] We can use index numbers to refer to any part of a array. ruby> ary[0] 1 ruby> ary[0,2] [1, 2] ruby> ary[0..1] [1, 2] ruby> ary[-2] 2 ruby> ary[-2,2] [2, "3"] ruby> ary[-2..-1] [2, "3"] (Negative indices mean offsets from the end of an array, rather than the beginning.)

Arrays can be converted to and from strings, using join and split respecitvely: ruby> str = ary.join(":") "1:2:3" ruby> str.split(":") ["1", "2", "3"] An associative array has elements that are accessed not by sequential index numbers, but by keys which can have any sort of value. Programming Ruby: The Pragmatic Programmer's Guide.