Is There a Ruby One-Line "Return If X"

is there a ruby one-line return if x?

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

Yes:

return value if condition

I love Ruby :-)

One line if statement not working

Remove if from if @item.rigged ? "Yes" : "No"

Ternary operator has form condition ? if_true : if_false

Shorthand for return x if x in Ruby

I'm just about certain that there exists no shorthand for your second example—nor could one be written without modifying the Ruby syntax—since it's not a common enough idiom. Sorry, bro, but it looks like you're going to have to be verbose on this one. (Though, really, as far as verbosity goes, this one isn't all that bad.)

(Note, too, that the first example isn't quite right: x ||= a is equivalent to x = x || a, which can also be expressed as x = a unless x.)

Is there a Python one-line idiom like x = y or return?

It's syntactically correct to do

...
if not (x := f(y)): return APPROPRIATE_ERROR
...

Generally, it's not recommended as standard style, but the option is there if you like it

Ruby - Using multiple conditions on a single line

This should do it:

if letters.eql?(letters.upcase) && dash.eql?('-') && numbers.to_i.to_s.eql?(numbers)

You can still wrap the entire conditional in parenthesis if you would like, but with Ruby (unlike JavaScript), you don't need to.

Conditionally assign return value of functions in one line

Not sure why you want to do this but this is valid ruby code and both methods will get called

x ||= a = myfunc; b = myfunc2; a || b

Both methods are called but on first run of this line, x will always be assigned to return of myfunc so I don't understand the purpose of this code.

Or maybe you want a random assignment of a or b ?

x ||= a = myfunc; b = myfunc2; [a,b].sample

Is there a one liner for this?

result = Product.search(query) and return result

Ruby if .. elsIf .. else on a single line?

a = (foo && "a" or bar && "b" or "c")

or

a = ("a" if foo) || ("b" if bar) || "c"

How do I define a method on one line in Ruby?

You can avoid the need to use semicolons if you use parentheses:

def hello() :hello end

Is it possible to have a one line each block in Ruby?

Yes, you can write:

cats.each { |cat| cat.name }

Or simply:

cats.each(&:name)

Note that Enumerable#each returns the same object you are iterating over (here cats), so you should only use it if you are performing some kind of side-effect within the block. Most likely, you wanted to get the cat names, in that case use Enumerable#map instead:

cat_names = cats.map(&:name)


Related Topics



Leave a reply



Submit