0

Found in the Ruby style guide.

1 > 2 ? true : false; puts 'Hi'

I assume this always returns Hi, but how do I read it?

3
  • Note: I understand the terneary operator (? :). The part that confuses me is ; puts "Hi" Commented Oct 3, 2012 at 2:55
  • It is a bad example. It does not mean much. Commented Oct 3, 2012 at 3:04
  • To expand on @sawa's comment, it was listed as an example after saying to use spaces after semicolons, and when to use spaces for other syntax. It's probably contrived because there's rarely a good reason to use semicolons - it's the only place in the style guide that mentions semicolons. Commented Oct 3, 2012 at 22:25

6 Answers 6

3

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Looks like I was overthinking this one.
2

You may read this like

1 > 2 ? true : false # first line of code
puts "Hi"  #second line of code

Comments

0

The Ruby compiler reads it like this:

1.>( 2 )
puts "Hi"

Ternary operator ? : is redundant. Comparison 'greater than' symbol :> is actually a method of Numeric class.

Comments

0

If 1 is greater than 2 then true, else then false. Then puts Hi

http://buddylindsey.com/c-vs-ruby-if-then-else/

Comments

0

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).

Comments

0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.