Ruby: what's the difference with these two Arrays?
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 fromfoostarting from the xth element.foo[x][y]finds the xth element infooand 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]
加载中,请稍侯......
精彩评论