def test_slicing_arrays
array = [:peanut, :butter, :and, :jelly]
assert_equal [:peanut], array[0,1]
assert_equal [:peanut, :butter], array[0,2]
assert_equal [:and, :jelly], array[2,2]
assert_equal [:and, :jelly], array[2,20]
assert_equal [], array[4,0]
assert_equal [], array[4,100]
assert_equal nil, array[5,0]
做這題的時候碰到了一些問題,我本來以為後面三個都會是nil,因為沒有array[4]可以抓,但是結果卻是要到[5]才會變成nil http://stackoverflow.com/questions/3568222/array-slicing-in-ruby-looking-for-explanation-for-illogical-behaviour-taken-fr
依照上面解釋的,slicing和indexing本身就是不一樣的
slice第一個變數定義的是元素之間的space,像下面這樣,4還是有在裡面的
:peanut :butter :and :jelly
0 1 2 3 4
Written with StackEdit.
沒有留言:
張貼留言