## Ruby如何返回两个值？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (33)

``````array = [1, 3, 5 , 6 ,7]
array[0], array[1] = array[1] , array[0] #=> [3, 1]
``````

### 2 个回答

``````foo = 1, 2, 3
# is the same as
foo = [1, 2, 3]
``````

``````a, b, c = ary
# is the same as
a = ary[0]
b = ary[1]
c = ary[2]
``````

``````a, b, c = not_an_ary
# is the same as
ary = not_an_ary.to_ary
a = ary[0]
b = ary[1]
c = ary[2]
``````

``````a, b, c = d, e, f
# is the same as
ary = [d, e, f]
a = ary[0]
b = ary[1]
c = ary[2]
``````

``````a, b, *c = ary
# is the same as
a = ary[0]
b = ary[1]
c = ary.drop(2) # i.e. the rest of the Array
``````

``````a, (b, c), d = ary
# is the same as
a = ary[0]
b, c = ary[1]
d = ary[2]
# which is the same as
a = ary[0]
b = ary[1][0]
c = ary[1][1]
d = ary[2]
``````

``````return 1, 2
next 1, 2
break 1, 2
yield 1, 2
# is the same as
return [1, 2]
next [1, 2]
break [1, 2]
yield [1, 2]
``````

``````def foo(a, (b, c), d) p a, b, c, d end

bar {|a, (b, c), d| p a, b, c, d }
``````

``````some_hash.each {|k, v| }
``````

``````some_hash.each {|(k, v)| }
``````

``````def nothing
end

nothing
# => nil
``````

``````def single
1
end

x = single
# => 1
``````

``````def multiple
return 1, 2
end

x = multiple
# => [ 1, 2 ]
x
# => [ 1, 2 ]
``````

``````x, y = multiple
# => [ 1, 2 ]
x
# => 1
y
# => 2
``````

``````a, b = 1, 2
# => [1, 2]
a, b = b, a
# => [2, 1]
a
# => 2
b
# => 1
``````