2
0
mirror of https://github.com/chubin/cheat.sheets synced 2024-11-05 12:00:16 +00:00
cheat.sheets/sheets/_ruby/control_flow

43 lines
840 B
Plaintext
Raw Normal View History

2018-10-07 23:56:57 +00:00
# Basic iteration
# Good ol' for-loop
for i in [1, 2, 3]
puts i
end
# Typically we don't use for-loops in Ruby, though.
# Rubyists tend to prefer .each
[1, 2, 3].each { |i| puts i }
# Using .each looks neater and it allows for powerful chaining
# of enumerable types.
2018-10-08 10:15:57 +00:00
#
2018-10-07 23:56:57 +00:00
# This example maps the array to [2, 4, 6] and prints each element.
[1, 2, 3].map { |i| i * 2 }.each { |i| puts i }
2018-10-08 10:15:57 +00:00
#
2018-10-07 23:56:57 +00:00
# Another kind of loop with specified iterations
10.times { puts 'test' }
10.times do |n|
puts "number #{n}"
end
# Conditionals
if 1 == 0
puts 'oh no'
elsif 1 == 1
puts "that's better"
else
puts 'cut it out'
end
# unless means 'if not'
unless 1 == 0
puts 'everything is ok'
end
# If the condition is short you can put it on one line.
happiness = 0 if 'my life'.empty?
# Or use ternary operator
happiness = 'my life'.empty? ? 0 : 100