Last active
June 23, 2016 18:50
-
-
Save itsjef/3479fa3adb23771aaa5889d45606e7ac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def func1(arr, output = [], i = 0) | |
| if i == arr.length | |
| output << arr # <= RING DING DING | |
| else | |
| for j in 0...arr.length | |
| arr[j] = i | |
| func1(arr, output, i+1) if arr[1].odd? | |
| end | |
| end | |
| output | |
| end | |
| def func2(arr, output = [], i = 0) | |
| if i == arr.length | |
| _arr = Array.new(arr) # <= Only by copying the method returns the correct output | |
| output << _arr | |
| else | |
| for j in 0...arr.length | |
| arr[j] = i | |
| func2(arr, output, i+1) if arr[1].odd? | |
| end | |
| end | |
| output | |
| end | |
| p func1 Array.new(2,1) #=> [[1, 0], [1, 0]] # | |
| p func2 Array.new(2,1) #=> [[1, 1], [1, 1]] # Desired output |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Vì Ruby là pass-by-value, nhưng trong trường hợp các Object có kích cỡ động như Array hoặc String thì tên biến là 1 pointer trỏ đến vùng lưu trữ object đó trong memory.
Khi truyền biến này vào 1 hàm hoặc copy nó thì tuy vẫn là pass-by-value nhưng giá trị được truyền vào là copy-của-pointer-đó, nghĩa là vẫn trỏ đến cùng ô nhớ trong memory, do vậy nên khi thao tác với nó vẫn sẽ gây ảnh hưởng đến giá trị tại ô nhớ được trỏ đến như thường.
Tạm gọi là pass-reference-by-value