Snowstormer Snowstormer - 27 days ago 6
Ruby Question

How to access method return from if statement in Ruby?

I have a method that returns an array, like this:

def foobar(foo, bar)
if foo != bar
[foo, bar]
end
end


Now, I want to call this method from inside my code using an if statement. How do I access the array values without having to duplicate the method?

if foobar("baz", "qux")
foo = foobar("baz", "qux")
puts foo[0], foo[1]
end


For further clarification, I mean something along the lines of
$~
when you call a regex match in an if statement.

Answer

Ruby has a concept called "local variables". You can assign objects to variables and then reference those variables:

if foo = foobar('baz', 'qux')
  puts foo[0], foo[1]
end

Note that Kernel#puts special-cases Array arguments and prints their elements on new lines, so your code is equivalent to the more idiomatic

if foo = foobar('baz', 'qux')
  puts foo
end
Comments