开发者

Ruby: what's the difference with these two Arrays?

开发者 https://www.devze.com 2023-01-07 23:02 出处:网络
Getting confused by syntax here, but what is the difference between: foo[x][y] 开发者_JAVA百科and

Getting confused by syntax here, but what is the difference between:

foo[x][y] 
开发者_JAVA百科

and

foo[x, y]


  • foo[x, n] returns n elements from foo starting from the xth element.
  • foo[x][y] finds the xth element in foo and returns its yth element.

Here's an example to demonstrate:

> foo = [[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14]]
=> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]
> foo[1,2]
=> [[3, 4, 5], [6, 7, 8]]
> foo[1][2]
=> 5


The other explanations are good, but here's a different take on it.

foo[x] is syntactic sugar for foo.slice(x). Likewise, foo[x,y] is equivalent to foo.slice(x,y). If you look at the rubydocs you'll see that

array.slice(index) returns the value at index, and

array.slice(start,length) with two parameters returns a subarray starting at start and having length elements.

Therefore, you can think of foo[x][y] as foo.slice(x).slice(y) which is taking the yth element from an array at position x of the foo array, which is obviously different from foo[x,y] or foo.slice(x,y) which is extracting a subarray of values from foo itself.


There first syntax lets you index into a 2D array (i.e. an array of arrays) e.g.

irb(main):035:0> l = [[1,2,3],[4,5,6],[7,8,9]]
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
irb(main):036:0> l[0]
=> [1, 2, 3]
irb(main):037:0> l[0][0]
=> 1

The second returns y elements from an array starting at position x e.g.

irb(main):038:0> a = [1,2,3,4,5,6,7,8]
=> [1, 2, 3, 4, 5, 6, 7, 8]
irb(main):039:0> a[2,3]
=> [3, 4, 5]
0

精彩评论

暂无评论...
验证码 换一张
取 消