Fellow Stranger
Fellow Stranger

Reputation: 34103

How to get and use the return value when if fails in conditional

def my_method
  "Happy New Year"
end  

if my_method.class == Integer
  ...
else
  ## How would I catch the return value "Happy New Year" and output it here, if the initial condition is not met?
end

(I'm sorry if I abuse the use of classes in my poor example.)

Upvotes: 0

Views: 111

Answers (2)

Jack Franklin
Jack Franklin

Reputation: 3765

You could do it by creating a variable within the conditional:

def my_method
    "Happy New Year"
end

if (x = my_method).class == Integer
  # do something
else
  puts x
end
#=> "Happy New Year"

This stores the result of the my_method call to the variable x, which you can then refer to. Of course, depending on the context in which you'll use this, you should come up with a better variable name than x.

Upvotes: 4

David Grayson
David Grayson

Reputation: 87516

For easiest reading, just make a local variable on the previous line:

result = my_method
if result.class == Integer
    ..
else
  puts result
end

Upvotes: 2

Related Questions