微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – <<和=有什么区别?

我一直在玩数组,并发现自己在理解以下代码时遇到了麻烦:
first_array = []
second_array = []
third_array = []                         # I initialized 3 empty arrays

third_array << [1,2,3,4,5,6,7,8,9]       # I loaded 1..9 into third_array[0]
puts third_array.size                    # => 1

first_array << third_array               # 1..9 was loaded into first_array[0]

second_array += third_array              # 1..9 was loaded into second_array[0]

puts first_array == third_array          # false
puts second_array == third_array         # true
puts first_array == second_array         # false

puts first_array.size                    # 1
puts second_array.size                   # 1
puts third_array.size                    # 1

这件事发生了什么?

second_array += third_array              # I have no clue

为什么并非所有阵列都相互相等?

解决方法

他们表现出相当不同的行为一个创建并分配一个新的Array对象,另一个修改现有的对象.

=将与second_array = second_array third_array相同.这会将消息发送到second_array对象,并将third_array作为参数传递.

根据文档Array.+返回通过连接两个数组构建的新数组对象.这将返回一个新对象.

Array.<<只需将参数推送到现有数组对象的末尾:

second_array = []
second_array.object_id = 1234

second_array += [1,4]
second_array.object_id = 5678

second_array << 5
second_array.object_id = 5678

参数的添加方式也有所不同.通过添加其他元素,它将有助于了解您的数组不相等的原因:

second_array = [1,3]

# This will push the entire object,in this case an array
second_array << [1,2]
# => [1,[1,2]]

# Specifically appends the individual elements,# not the entire array object
second_array + [4,5]
# => [1,2],5]

这是因为Array.使用连接而不是推送.与修改现有对象的数组Array.concat不同.返回一个新对象.

你可以想到一个Ruby实现,如:

class Array
  def +(other_arr)
    dup.concat(other_arr)
  end
end

在您的特定示例中,您的对象在最后看起来像这样:

first_array  = [[[1,9]]] # [] << [] << (1..9).to_a
second_array =  [[1,9]]  # [] + ([] << (1..9).to_a)
third_array  =  [[1,9]]  # [] << (1..9).to_a

原文地址:https://www.jb51.cc/ruby/266891.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐