The Ruby Programming Language

Datatypes

#Arrays
a = [1, 2, "hi", :yo] #anything goes
a[0] #  1
a[-1] # :yo, negative counts from end
a.length # 4
a[1..3]  #  [2, "hi", :yo] This is a Range
a[1...3] # [2, "hi"] Three dots exclude end

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| puts digit}  #prints 0 to 9

#Hashes
h={:grade => 88, 'name' => 'Peter', :age => 23}
h['name']  # "Peter"
h['grade'] # nil
h[:grade]  # 88

#Numbers
6.times do
  puts "Hi" #writes it 6 times.
end
1.upto(5) {print "hi"}
99.downto(95) {print "hi"}
50.step(80.5) {print "hi"}

#Regular expressions, like Perl
b = /^\s*[a-z]/ #define a regexp

name = "Fats Waller"
name =~ /a/ # 1, it contains a
name =~ /z/ # 0, but not z
/a/ =~ name # 1
#Sideffect of a match is setting variables:
$& #contains the text of the match




José M. Vidal .

2 of 11