Mr. Kennedy Mr. Kennedy - 1 year ago 69
Ruby Question

What condition is my Ruby conditional in?

The following conditional syntax displays the string 'is true' in irb without using


irb(main):001:0> if true
irb(main):002:1> 'is true'
irb(main):003:1> else
irb(main):004:1* 'is false'
irb(main):005:1> end
=> "is true"

...yet when I invoke the same syntax in a script and run it from the command line, it gets ignored. Why?

# Odd behaviour:
puts "Why do only two of the three conditionals print?"

# This doesn't put anything to screen:
if true
'is true_1'
'is false'

puts "Seriously, why? Or better yet: how?"

# But this does:
if true
puts 'is true_2'
puts 'is false'

# And this works without "puts":
def truthiness
if 1.send(:==, 1)
'is true_3'
'is false'

puts truthiness
puts "Weird."

When I run this as a script, it displays:

"Why do only two of the three conditionals print?
Seriously, why? Or better yet: how?
is true_2
is true_3

FWIW, I am following along with Sandi Metz's talk "Nothing is Something"
...and listening to this:
Apologies as I am new to Ruby and trying to wrap my head around how it does what it does.

Useful resources:

Answer Source

The IRB output here is showing the return value of the operation, which is not necessarily what is printed to STDOUT (i.e. the terminal) during execution.

Your script is just throwing the return value away, you would have to do this:

val = if true
        'is true_1'
        'is false'

puts val
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download