Mr. Kennedy Mr. Kennedy - 2 months ago 8
Ruby Question

What condition is my Ruby conditional in?

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

puts


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'
else
'is false'
end

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

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

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

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
Weird."


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

EDIT:
Useful resources:

http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-puts

http://programmers.stackexchange.com/questions/150824/is-the-puts-function-of-ruby-a-method-of-an-object

Answer

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'
      else
        'is false'
      end

puts val