Ruby 如何返回两个值? [英] How does Ruby return two values?

查看:37
本文介绍了Ruby 如何返回两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我交换数组中的值时,我都会确保将其中一个值存储在引用变量中.但我发现 Ruby 可以返回两个值以及自动交换两个值.例如,

Whenever I swap values in an array, I make sure I stored one of the values in a reference variable. But I found that Ruby can return two values as well as automatically swap two values. For example,

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

我想知道 Ruby 是如何做到这一点的.

I was wondering how Ruby does this.

推荐答案

与其他语言不同,Ruby 中任何方法调用的返回值总是一个对象.这是可能的,因为与 Ruby 中的所有内容一样,nil 本身就是一个对象.

Unlike other languages, the return value of any method call in Ruby is always an object. This is possible because, like everything in Ruby, nil itself is an object.

您会看到三种基本模式.不返回特定值:

There's three basic patterns you'll see. Returning no particular value:

def nothing
end

nothing
# => nil

返回奇异值:

def single
  1
end

x = single
# => 1

这符合您对其他编程语言的期望.

This is in line with what you'd expect from other programming languages.

处理多个返回值时情况会有所不同.这些需要明确指定:

Things get a bit different when dealing with multiple return values. These need to be specified explicitly:

def multiple
  return 1, 2
end

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

在调用返回多个值时,您可以将它们分解为独立变量:

When making a call that returns multiple values, you can break them out into independent variables:

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

这个策略也适用于你所说的那种替代:

This strategy also works for the sorts of substitution you're talking about:

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

这篇关于Ruby 如何返回两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆