is there a ruby one-line "return if x"?

35,354

Solution 1

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

Yes:

return value if condition

I love Ruby :-)

Solution 2

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.

Solution 3

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)}"
Share:
35,354
jpw
Author by

jpw

Updated on July 09, 2022

Comments

  • jpw
    jpw almost 2 years

    have a ton of places I need to add

    if this_flag
      return
    end
    

    can that be done on one line with ruby?

  • jpw
    jpw over 13 years
    i'm getting there too... just KNEW they'd have a shortcut!
  • Ryanmt
    Ryanmt over 13 years
    Yes, the method definition will return nil. However, calling the method will return different things... depending. returner(true) => "success" While returner(false) => nil