Ruby - Flow, Conditionals
- each
Practice Using {|e| e} to make shorten lines. After finishing writing code, working without issues, then try to make it shorten.
REMEBER, right now, as a learner, my code is never can be perfect as I wrote. Check other people’s code a lot and copy good part.
for num in [1,2,3]
puts num
end
[1,2,3].each {|num| puts num}
- Ternary operator [if/else] > only 2 condition
age = 20
if age > 18
puts "Adult"
else
puts "Boy"
#condition ? code_when_truthy : code_when_falsey
score= 50
result = score > 40 ? 'Pass' : 'Fail'
puts result
- if elsif elsif else = Case / when > several condition
Use CASE/WHEN in case of have more than 5 cases, less than 5 cases, using method would be better. Short codes, easy to understand.
num = 42
case num
when 1
puts "one"
when 2
puts "two"
when 42
puts "the answer!"
else
puts "nope"
end
Don’t forget the else statement at the end if you want to be exhaustive!