jpw
jpw

Reputation: 19247

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

have a ton of places I need to add

if this_flag
  return
end

can that be done on one line with ruby?

Upvotes: 43

Views: 46051

Answers (4)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

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

Yes:

return value if condition

I love Ruby :-)

Upvotes: 131

3therk1ll
3therk1ll

Reputation: 2421

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)}"

Upvotes: 1

Ryanmt
Ryanmt

Reputation: 3265

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.

Upvotes: 6

user166390
user166390

Reputation:

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.

Upvotes: 10

Related Questions