Sarah L
Sarah L

Reputation: 21

Conditional assignment from a function with multiple return values in Ruby?

Is there a way to use the conditional assignment operator (||=) to assign to a particular value from a function that returns multiple values?

For example, I've seen this pattern a lot:

def foo
  'hello'
end

def bar
  @bar ||= foo
end

This works great if foo returns a single value. What about if foo returns two values, and I only want to assign bar to the first value?

def foo
  return 'hello', 'world'
end

def bar
  @bar ||= foo
end

# How to set bar = 'hello' ?

Is there some way to conditionally assign to only the first value returned? If not -- what would be the idiomatic way to set the bar instance variable to 'hello'?

(EDITED: fixed typo in foo in second example -- forgot to explicitly return.)

Upvotes: 0

Views: 407

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70387

Ruby doesn't support multiple return values. It's simply syntax sugar for returning a list. Hence, the following works.

@bar ||= foo[0]

Upvotes: 2

Related Questions