Found in the Ruby style guide.
1 > 2 ? true : false; puts 'Hi'
I assume this always returns Hi, but how do I read it?
Found in the Ruby style guide.
1 > 2 ? true : false; puts 'Hi'
I assume this always returns Hi, but how do I read it?
If 1 > 2 then true, else it is false.
However, it will print hi whatever the condition result.
It is the same that:
if 1 > 2 then
true
else
false
end
puts 'hi'
If 1 is greater than 2 then true, else then false. Then puts Hi
The semicolon is an inline way of separating two lines of code. So it's just like
1 > 2 ? true : false
puts "Hi"
which is equivalent to
false
puts "Hi"
And of course a line that just says false will do nothing (except for a few cases, like if it's the last line of a function definition in which case the method returns false if it reaches that line).
1 > 2 ? true : false; puts "Hi" that means
if 1 > 2
return true
else
return false
end
puts "Hi"
Here each time means the result is whatever it will print "hi" because we print "Hi" in outside of condition.
but
if 1 > 2
puts "1 is not greater than 2"
else
puts "1 is greater than 2"
end
you can also test in your console
1.9.3p125 :002 > if 1 > 2
1.9.3p125 :003?> puts "1 is not greater than 2"
1.9.3p125 :004?> else
1.9.3p125 :005 > puts "1 is greater than 2"
1.9.3p125 :006?> end
1 is greater than 2
=> nil