How Does Ruby Return Two Values

Return two and more values from a method

def sumdiff(x, y)
return x+y, x-y
end
#=> nil

sumdiff(3, 4)
#=> [7, -1]

a = sumdiff(3,4)
#=> [7, -1]
a
#=> [7, -1]

a,b=sumdiff(3,4)
#=> [7, -1]
a
#=> 7
b
#=> -1

a,b,c=sumdiff(3,4)
#=> [7, -1]
a
#=> 7
b
#=> -1
c
#=> nil

Multiple return values with arrays and hashes

What you are asking is syntactically not possible.

What you want to accomplish is possible, but you will have to code it.
One possible way to do that is shown below

hash = {"a" => 1, "b" => 2}

# Assign new keys
new_keys = ["c", "d"]
p [new_keys, hash.values].transpose.to_h
#=> {"c"=>1, "d"=>2}

# Assign new values
new_values = [3, 4]
p [hash.keys, new_values].transpose.to_h
#=> {"a"=>3, "b"=>4}

If you really want some more easier looking way of doing, you could monkey-patch Hash class and define new methods to manipulate the values of keys and values array. Please be cautioned that it may not be really worthwhile to mess with core classes. Anyways, a possible implementation is shown below. Use at your own RISK.

class Hash
def values= new_values
new_values.each_with_index do |v, i|
self[keys[i]] = v if i < self.size
end
end
def keys= new_keys
orig_keys = keys.dup
new_keys.each_with_index do |k, i|
if i < orig_keys.size
v = delete(orig_keys[i])
self[k] = v
rehash
end
end
end
end

hash = {"a" => 1, "b" => 2}

hash.values = [2,3]
p hash
#=> {"a"=>2, "b"=>3}

hash.keys = ["c", "d"]
p hash
#=> {"c"=>2, "d"=>3}

hash.keys, hash.values = ["x","y"], [9, 10]
p hash
#=> {"x"=>9, "y"=>10}

hash.keys, hash.values = ["x","y"], [9, 10]
p hash
#=> {"x"=>9, "y"=>10}

# *** results can be unpredictable at times ***
hash.keys, hash.values = ["a"], [20, 10]
p hash
#=> {"y"=>20, "a"=>10}

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

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

@bar ||= foo[0]

Stubbing a method that returns multiple values rspec

Ruby does not have multivalue returns. The code example provided implicitly returns an array with 2 elements, i.e. return "foo", "bar" is same as return ["foo", "bar"].

So the correct way to stub is:

allow(@my_foo_instance).to receive(:returns_two_things) \
.and_return(["foo", "bar"])

Returning Multiple Values From Map

Use Enumerable#flat_map

b = [0, 3, 6]
a = b.flat_map { |x| [x, x+1, x+2] }
a # => [0, 1, 2, 3, 4, 5, 6, 7, 8]

Ruby prime_division returning two values,

15.prime_division.map(&:first) # => [3, 5]

The 1s in the result stand for the number of occurrences (aka one 3 and one 5).

Ruby: Separating Multiple Returns

What @matthew says. Or this:

def returnThreeValues
return 1, *returnTwoValues
end


Related Topics



Leave a reply



Submit