Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

ruby

People also ask

Does Ruby have return?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.

What is an implicit return in Ruby?

Ruby has implicit returns. This means that if a return is the last expression in a path of execution, there's no need for the return keyword. Worth noting is that return 's default argument is nil , which is a falsey value.

What does return in Ruby do?

Explicit return Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.

How do you return a string in Ruby?

In Ruby functions, when a return value is not explicitly defined, a function will return the last statement it evaluates. If only a print statement is evaluated, the function will return nil . The above will print the string printing , but return the string returning .


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

Yes:

return value if condition

I love Ruby :-)


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.


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.


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