to_ato_ary之间有什么区别?

推荐答案

to_ary用于implicit次转换,而to_a用于explict次转换.

例如:

class Coordinates
  attr_accessor :x, :y

  def initialize(x, y); @x, @y = x, y end

  def to_a; puts 'to_a called'; [x, y] end

  def to_ary; puts 'to_ary called'; [x, y] end

  def to_s; "(#{x}, #{y})" end

  def inspect; "#<#{self.class.name} #{to_s}>" end
end

c = Coordinates.new 10, 20
# => #<Coordinates (10, 20)>

splat运算符(*)是explicit转换为数组的一种形式:

c2 = Coordinates.new *c
# to_a called
# => #<Coordinates (10, 20)>

另一方面,并行赋值是implicit到数组的转换形式:

x, y = c
# to_ary called
puts x
# 10
puts y
# 20

在块参数中捕获集合成员也是如此:

[c, c2].each { |(x, y)| puts "Coordinates: #{x}, #{y}" }
# to_ary called
# Coordinates: 10, 20
# to_ary called
# Coordinates: 10, 20

ruby-1.9.3-p0个样本进行测试.

这种模式似乎在Ruby语言中被广泛使用,to_sto_strto_ito_int等方法对以及可能更多的方法就证明了这一点.

参考资料:

Ruby相关问答推荐

使用map DO使用嵌套数组重构对象数组

从同名方法调用 ruby​​ 中的方法

Ruby 中无法解释的撬动行为

RVM 和 OpenSSL 的问题

带有索引的 Ruby `each_with_object`

Ruby gem 权限被拒绝 /var/lib/gems 使用 Ubuntu

如何找到安装 Ruby Gem 的路径(即 Gem.lib_path c.f. Gem.bin_path)

Ruby 的排序方法使用哪种算法?

Ruby 的 File.open 给出没有这样的文件或目录 - text.txt (Errno::ENOENT)错误

Vagrant - 如何拥有特定于主机平台的配置步骤

你能用 Ruby 开发原生 iPhone 应用程序吗?

如何在 ruby​​ net/http 中实现 cookie 支持?

`respond_to?` 与 `respond_to_missing?`

Ruby:更新哈希值的最简单方法是什么?

相当于 Ruby 中的通过

为什么 Ruby 的 Date 类会自动加载,但 DateTime 不会?

将 CSV 文件转换为哈希数组

Ruby 将 CSV 文件读取为 UTF-8 和/或将 ASCII-8Bit 编码转换为 UTF-8

如何理解 class_eval() 和 instance_eval() 的区别?

Ruby中的字符串和符号有什么区别?