0

I've been studying arrays in Ruby. Specifically the effects of manipulating arrays with a[start, count] and a[lower_range..upper_range] in the Ruby Programming 1.9 book.

Specifically, if I have:

a = [1, 3, 5, 7, 9]

and I do the following:

a[2, 2] = 'cat'

I get the output for a: a => [1, 3, "cat", 9]

Instead of what I expected to be [1, 3, "cat", "cat", 9]

Edit: Thank you everyone for your input. All of the methods suggested work. I understand now.

I prefer the Array.new method that was suggested, because with an arbitrary range, like a[2, n], I can simply use, a[2, n] = Array.new(n, "cat")

Fantastic, thanks everyone.

4

4 回答 4

4

将其视为用右侧的所有内容替换等号左侧的所有内容。您正在用一个元素替换一个数组。如果你想用多个元素替换它,请使用a[2, 2] = Array.new(2, 'cat')

于 2013-05-10T21:47:45.133 回答
3

发生的情况是索引 2 中的两个值被“cat”替换。您可以在以下位置看到:

a = [1, 3, 5, 7, 9]
a[2,2] # => = [5, 7]
a[2,2] = 'cat'
a # => [1, 3, 'cat', 9]

因此,使用array[start, count]andarray[range_start .. range_end]替换数组的那一部分,而不是该范围内的所有索引。

于 2013-05-10T21:51:55.827 回答
3

你选择了错误的方法。[]进行元素分配(替换另一个选定范围)

你真正要找的是fill

a = [1, 3, 5, 7, 9]
#=> [1, 3, 5, 7, 9]
a.fill('cat', 2, 2)
#=> [1, 3, "cat", "cat", 9]
于 2013-05-10T21:55:26.980 回答
2

元素分配的工作方式类似于替换定义的范围。看看这个用法的 Ruby 文档。此分配将位置 2 中的两个数组条目替换为您的 RHS 表达式。以下表达式应该达到您期望的结果:

a[2, 2] = ['cat', 'cat']

:)

于 2013-05-10T21:57:12.690 回答