ruby新的数组实例,哈希

时间:2013-12-18 17:31:30

标签: ruby

很抱歉,如果这个问题是如此虚假

我想知道

的区别
a = Array.new  and a = []
b = Hash.new   and b = {}

获取新实例的首选方法是什么?

由于

4 个答案:

答案 0 :(得分:2)

最好使用[]{},因为您可以重新定义initializeArray的{​​{1}}方法,因此它可能不可靠。

示例:

Hash

class Array def initialize # cause chaos end end []也更短:)

问题的一个扩展示例是:

{}

答案 1 :(得分:1)

[]{}已经过精心设计,可以让您的生活更美好=) 没有理由你不应该使用它们。

答案 2 :(得分:1)

在常规空文字的情况下,两者之间没有区别。 []{}更为传统。

当你需要做一些更高级的事情时,实际的差异就来了。文字允许您指定数组或散列的内容,而new方法允许您执行诸如使用任意数量的相同对象创建数组,或者默认值不是nil的散列。< / p>

答案 3 :(得分:1)

Array.new可用于以三种不同的方式创建数组:

来自ruby-doc网站的逐字:

new(size = 0,obj = nil)     新的(阵列)     new(size){| index |块}     返回一个新数组。

In the first form, if no arguments are sent, the new array will be empty. When a size and an optional obj are sent, an array is created with size copies of obj. Take notice that all elements will reference the same object obj.

The second form creates a copy of the array passed as a parameter (the array is generated by calling #to_ary on the parameter).

first_array = ["Matz", "Guido"]

second_array = Array.new(first_array) #=> ["Matz", "Guido"]

first_array.equal? second_array       #=> false
In the last form, an array of the given size is created. Each element in this array is created by passing the element’s index to the given block and storing the return value.

Array.new(3){ |index| index ** 2 }
# => [0, 1, 4]
Common gotchas¶ ↑

When sending the second parameter, the same object will be used as the value for all the array elements:

a = Array.new(2, Hash.new)
# => [{}, {}]

a[0]['cat'] = 'feline'
a # => [{"cat"=>"feline"}, {"cat"=>"feline"}]

a[1]['cat'] = 'Felix'
a # => [{"cat"=>"Felix"}, {"cat"=>"Felix"}]
Since all the Array elements store the same hash, changes to one of them will affect them all.

If multiple copies are what you want, you should use the block version which uses the result of that block each time an element of the array needs to be initialized:

a = Array.new(2) { Hash.new }
a[0]['cat'] = 'feline'
a # => [{"cat"=>"feline"}, {}]

[]为您创建一个空数组

Hash.new{}

的上述内容类似