>> x = 6?>ifx>3then?> puts "greater!!">>endgreater!!# else>> x = 2?>ifx>3then?> puts "greater!!"?>else?> puts "lower!!">>endlower!!>>puts"greater!!"ifx>1greater!!
# Opposite of 'if' statement>> x =5=>unless x ==10thenprint"#{x}"end=>print"#{x}"unless x ==10
=> x =5>>case x|when1print"one"|when2print"two"|when3print"three"|elseprint"no idea"|end# Assign the return value to a variable>> id =2000>> name =case|when id ==1111then"Mark"|when id ==1112then"Bob"|when id >=2000then"Other">> id=>2000>> name=>Other
(1..10) ===4# Use triple equal sign
name ="Bob"name =="Bob"?"Hi Bob":"Who are you?"
Loops
# Repeats a block of code until the test expression is evaluated to false>> i =0?>while i <5do?>print i = i +1,"\s">>end12345=>nil>> i =0>>print i = i +1,"\s"while i <512345
# Repeats a block of code until the test expression is evaluated to true>> i =5?>until i ==0?>print i-=1,"\s">>end43210=>nil>> i =5>>print i-=1,"\s"until i ==043210=>nil
# iterates through the elements of an enumerable object?>for i in [10,20,4] do?>print i,"\s">>end10204=> [10,20,4]
>> hash = {:name =>"fer", :gender =>"maple" }?>for key, value in hash?>print"#{key}:#{value}\n">>endname:fergender:maple
?>for i in1..10?>print"#{i}\s">>end12345678910=>1..10
>> array=> [1,4,9,16,25]>> array.select { |x| x >10 }=> [16,25]
# oposite of select>> array=> [1,4,9,16,25]>> array.reject { |x| x >10 }=> [1,4,9]
>> array = [1,2,3,4,5]>> array.inject { |sum, x| sum + x}=>15>> array.inject(100) { |sum, x| sum + x}=>115
Enumerator: object whose purpose is to enumerate another enumerable object. This means that enumerators are enumerable too.
If you have a method that uses an enumerable object, you may not want to pass the enumerable collection object because it is mutable and the method may modify it.
So you can pass an enumerator created with to_enum and nothing will happen to the original enumerable collection
>> a = [1,2,3,4]=> enum = a.to_enum>> enum.next=>1>> enum.next=>2
Altering structured control flow (break/next)
>>for i in1..10|print i,"\s"|breakif i ==5|end=>12345=>nil>> (1..10).each do|i||print i,"\s"|breakif i ==5|end=>12345=>nil
# The next statement ends the current iteration and jumps to the next one.>>for i in1..10|print i,"\s"|nextif i ==5|end=>1234678910=>nil
# Redo restarts the current iteration from th efirst instruction in the body# of the loop or iteration>> sum =0=>0>>forin i in1..3| sum +=1|redoif sum ==1|end=>1..3>> sum=>7>>1+2+3=>6
BEGIN/END
These are two reserved words in Ruby.
# BEGIN allows the execution of Ruby code at the beginning of a Ruby program# END allow sthe execution if Ruby code at the end of a Ruby programBEGIN {puts"Beginning"}END {puts"Ending"}puts"Normal control flow"=>BeginningNormal control flowEnding
BEGIN {puts1}BEGIN {puts2}BEGIN {puts3}END {puts4}END {puts5}END {puts6}=>123654