43

have a ton of places I need to add

if this_flag
  return
end

can that be done on one line with ruby?

3
  • 7
    Why not test this out before asking? Use irb and play around with what you can and CAN do with Ruby :)
    – aarona
    Mar 25, 2011 at 17:38
  • 3
    @DJTripleThread: Makes me want to create "Let me IRB that for you". Mar 27, 2011 at 22:33
  • 4
    for haters like the above two, please note the excellent RANGE of answers supplied below, that highlight the power of ruby (instead of whining about the one obvious answer being obvious). That is the power of SO and that is why I will never apologize for asking an 'obvious' question.
    – jpw
    Feb 28, 2016 at 18:44

4 Answers 4

129

is there a ruby one-line “return if x” ?

Yes:

return value if condition

I love Ruby :-)

1
  • 3
    i'm getting there too... just KNEW they'd have a shortcut!
    – jpw
    Mar 25, 2011 at 17:44
9

Some additions to Jörg W Mittag's good answer:

x && return
x and return
if x then return end

I do not actually recommend the first two forms: however, the above examples are all valid productions. I personally prefer to avoid return in general -- most grammar constructs in Ruby are usable expressions.

Happy coding.

0
6

Ruby always returns the last thing... Why not just structure your code differently?

def returner(test)    
  "success" if test   
end

Whatever you've done last will return. I love Ruby.

1
  • 1
    Yes, the method definition will return nil. However, calling the method will return different things... depending. returner(true) => "success" While returner(false) => nil
    – Ryanmt
    Mar 25, 2011 at 20:13
1

Create a method that check for the expected class types Example below. Method check_class will return true as soon as it finds the correct class. Useful if you may need to expand the number of different class types for any reason.

def check_class(x)
  return true if is_string(x) 
  return true if is_integer(x)
  # etc etc for possible class types
  return false # Otherwise return false
end

def is_string(y)
  y.is_a? String
end

def is_integer(z)
  z.is_a? Integer
end


a = "string"
puts "#{check_class(a)}"

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.