Learning Ruby 4, Number, String and Range

Numbers
Fixnum Bignum
123456                  => 123456   # Fixnum
0d123456                => 123456   # Fixnum
123_456                 => 123456   # Fixnum – underscore ignored
-543                    => -543     # Fixnum – negative number
0xaabb                  => 43707    # Fixnum – hexadecimal
0377                    => 255      # Fixnum – octal
-0b10_1010              => -42      # Fixnum – binary (negated)
123_456_789_123_456_789 => 123456789123456789 # Bignum

?a       => 97  # ASCII character
?
      => 10  # code for a newline (0x0a)
?C-a    => 1   # control a = ?A & 0x9f = 0×01
?M-a    => 225 # meta sets bit 7
?M-C-a => 129 # meta and control a
?C-?    => 127 # delete character

iterators
    3.times        { print "X "}
    1.upto(5)      {|i| print i, " " }
    99.downto(95)  {|i| print i, " " }
    50.step(80, 5) {|i| print i, " " }
produces:
    X X X 1 2 3 4 5 99 98 97 96 95 50 55 60 65 70 75 80

Strings
Double-quoted & single-quoted strings
'escape using "\"'   escape using ""
                    →
'That's right'       That's right
                    →
"Seconds/day: #{24*60*60}"      Seconds/day: 86400
                              →
"#{'Ho! '*3}Merry Christmas!"   Ho! Ho! Ho! Merry Christmas!
                              →
"This is line #$."              This is line 3
                              →
#{ expr }. If the code is just a global variable, a class variable, or an instance variable,you can omit the braces.
    puts  "now is #{ def the(a)
                        'the ' + a
                      end
                      the('time')
                    } for all good coders…"
produces:
    now is the time for all good coders…

to construct string literals
%q/general single-quoted string/   general single-quoted string
                                 →
%Q!general double-quoted string!   general double-quoted string
                                 →
%Q{Seconds/day: #{24*60*60}}       Seconds/day: 86400
                                 →
string = <<END_OF_STRING
    The body of the string
    is the input lines up to
    one ending with the same
    text that followed the '<<'
END_OF_STRING

delimiter
 If it is an opening bracket “[”, brace “{”, parenthesis “(”, or less-than sign “<”, the string is read until the matching close symbol is found. Otherwise the string is read until the next occurrence of the same
1.8 delimiter. The delimiter can be any nonalphanumeric or nonmultibyte character.

mins, secs = length.split(/:/)
mins, secs = length.scan(/d+/)

class WordIndex
  def initialize
    @index = {}
  end
  def add_to_index(obj, *phrases)
    phrases.each do |phrase|
      phrase.scan(/w[-w']+/) do |word|   # extract each word
        word.downcase!
        @index[word] = [] if @index[word].nil?
        @index[word].push(obj)
      end
    end
  end
  def lookup(word)
    @index[word.downcase]
  end
end
 the exclamation mark at the end of the ?rst downcase! method is an indication that the method will modify the receiver in place

Ranges
Ranges as Sequences
The two-dot form creates an inclusive range, and the three-dot form creates a range that excludes the speci?ed high value.
1..10
'a'..'z'
my_array = [ 1, 2, 3 ]
0…my_array.length

(1..10).to_a          [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
                    →
('bar'..'bat').to_a   ["bar", "bas", "bat"]
                    →

digits = 0..9
digits.include?(5)                   true
                                   →
digits.min                           0
                                   →
digits.max                           9
                                   →
digits.reject {|i| i < 5 }           [5, 6, 7, 8, 9]
                                   →
digits.each {|digit| dial(digit) }   0..9
   
                 
         
spaceship operator
<=> compares two values, returning −1, 0, or +1 depending on whether the ?rst is less than, equal to, or greater than the second.

class VU
  include Comparable
  attr :volume
  def initialize(volume)  # 0..9
    @volume = volume
  end
  def inspect
    '#' * @volume
  end
  # Support for ranges
  def <=>(other)
    self.volume <=> other.volume
  end
  def succ
    raise(IndexError, "Volume too big") if @volume >= 9
    VU.new(@volume.succ)
  end
end

medium_volume = VU.new(4)..VU.new(7)
medium_volume.to_a                    [####, #####, ######, #######]
                                    →
medium_volume.include?(VU.new(3))     false
                                    →

Ranges as Conditions

Ranges as Intervals
seeing if some value falls within the interval represented by the range.
(1..10)    === 5         true
                       →
(1..10)    === 15        false
                       →
(1..10)    === 3.14159   true
                       →
('a'..'j') === 'c'       true
                       →
('a'..'j') === 'z'       false

此條目發表在 Ruby on Rails 分類目錄。將固定鏈接加入收藏夾。

發表評論