[ 3, 1, 7, 0 ].sort.reverse [7, 3, 1, 0]
Operator Expressions
a*b + c
(a.*(b)).+(c)
Miscellaneous Expressions
Command Expansion
`date` "Thu Aug 26 22:36:31 CDT 2004
"
`ls`.split[34] "book.out"
%x{echo "Hello there"} "Hello there
"
for i in 0..3
status = `dbmanager status id=#{i}`
# …
end
Assignment
a=b=1+2+3
a →6
b →6
a = (b = 1 + 2) + 3
a →6
b →3
attribute
de?ne a writable object attribute
class Song
def duration=(new_duration)
@duration = new_duration
end
end
attribute assignment
song.duration = 234
Parallel Assignment
swap the values in two variables
a, b = b, a
x=0 0
a, b, c = x, (x += 1), (x += 1) [0, 1, 2]
a = [1, 2, 3, 4]
b, c = a b == 1, c == 2
b, *c = a b == 1, c == [2, 3, 4]
b, c = 99, a b == 99, c == [1, 2, 3, 4]
b, *c = 99, a b == 99, c == [[1, 2, 3, 4]]
b, c = 99, *a b == 99, c == 1
b, *c = 99, *a b == 99, c == [1, 2, 3, 4]
Nested Assignments
b, (c, d), e = 1,2,3,4 b == 1, c == 2, d == nil, e == 3
b, (c, d), e = [1,2,3,4] b == 1, c == 2, d == nil, e == 3
b, (c, d), e = 1,[2,3],4 b == 1, c == 2, d == 3, e == 4
b, (c, d), e = 1,[2,3,4],5 b == 1, c == 2, d == 3, e == 5
b, (c,*d), e = 1,[2,3,4],5 b == 1, c == 2, d == [3, 4], e == 5
Other Forms of Assignment
Conditional Execution
The number zero is not interpreted as a false value. Neither is a zero-length string.
De?ned?, And, Or, and Not
and and or have the same precedence,
&& has a higher precedence than ||.
defined? 1 "expression"
defined? dummy nil
defined? printf "method"
defined? String "constant"
defined? $_ "global-variable"
defined? Math::PI "constant"
defined? a=1 "assignment"
defined? 42.abs "method"
Operator Meaning
== Test for equal value.
=== Used to compare the each of the items with the target in the when clause of a case statement.
<=> General comparison operator. Returns −1, 0, or +1, depending on whether its receiver is less than, equal to, or greater than its argument.
<, <=, >=, > Comparison operators for less than, less than or equal, greater than or equal, and greater than.
=~ Regular expression pattern match.
eql? True if the receiver and argument have both the same type and equal values. 1 == 1.0 returns true, but 1.eql?(1.0) is false.
equal? True if the receiver and argument have the same object ID.
== and =~ have negated forms, != and !~.
The value of Logical Expressions
nil and true nil
false and true false
99 and false false
99 and nil nil
99 and "cat" "cat"
false or nil nil
nil or false false
99 or false 99
words[key] ||= []
words[key] << word
=====>
(words[key] ||= []) << word
If and Unless Expressions
then
if song.artist == "Gillespie" then handle = "Dizzy"
elsif song.artist == "Parker" then handle = "Bird"
else handle = "unknown"
end
:
if song.artist == "Gillespie": handle = "Dizzy"
elsif song.artist == "Parker": handle = "Bird"
else handle = "unknown"
end
if song.artist == "Gillespie"
handle = "Dizzy"
elsif song.artist == "Parker"
handle = "Bird"
else
handle = "unknown"
end
unless song.duration > 180
cost = 0.25
else
cost = 0.35
end
==>
cost = song.duration > 180 ? 0.35 : 0.25
If and Unless Modi?ers
mon, day, year = $1, $2, $3 if date =~ /(\d\d)-(\d\d)-(\d\d)/
puts "a = #{a}" if debug
print total unless total.zero?
Case Expressions
leap years must be divisible by 400, or divisible by 4 and not by 100.
leap = case
when year % 400 == 0: true
when year % 100 == 0: false
else year % 4 == 0
end
case input_line
when "debug"
dump_debug_info
dump_symbols
when /p\s+(\w+)/
dump_variable($1)
when "quit", "exit"
exit
else
print "Illegal command: #{input_line}"
end
case shape
when Square, Rectangle
# …
when Circle
# …
when Triangle
# …
else
# …
end
Loops
while line = gets
# …
end
until play_list.duration > 60
play_list.add(song_list.pop)
end
a=1
a *= 2 while a < 100
a -= 10 until a < 100
a → 98
file = File.open("ordinal")
while line = file.gets
puts(line) if line =~ /third/ .. line =~ /fifth/
end
produces:
third
fourth
fifth
Iterators
3.times do
print "Ho! "
end
produces:
Ho! Ho! Ho!
0.upto(9) do |x|
print x, " "
end
produces:
0123456789
0.step(12, 3) {|x| print x, " " }
produces:
0 3 6 9 12
[ 1, 1, 2, 3, 5 ].each {|val| print val, " " }
produces:
11235
For . . . In
for song in songlist
song.play
end
for i in ['fee', 'fi', 'fo', 'fum']
print i, " "
end
for i in 1..3
print i, " "
end
for i in File.open("ordinal").find_all {|line| line =~ /d$/}
print i.chomp, " "
end
produces:
fee fi fo fum 1 2 3 second third
Break, Redo, and Next
while line = gets
next if line =~ /^\s*#/ # skip comments
break if line =~ /^END/ # stop at end
# substitute stuff in backticks and try again
redo if line.gsub!(/`(.*?)`/) { eval($1) }
# process line …
end
Retry
for i in 1..100
print "Now at #{i}. Restart? "
retry if gets =~ /^y/i
end
Running this interactively, you may see
Now at 1. Restart? n
Now at 2. Restart? y
Now at 1. Restart? n
…
Variable Scope, Loops, and Blocks
x = nil
y = nil
[ 1, 2, 3 ].each do |x|
y=x+1
end
[ x, y ] → [3, 4]
if false
a=1
end
3.times {|i| a = i }
a 2