N
Nathan Morse
I was talking to a coworker today about the Ruby, and we were
discussing how in Ruby everything is an object. He wondered if
everything was call-by-reference, and my knee jerk reaction was yes.
Then I ran the following irb session....
------------------- START IRB -------------------------
def foo(x)
x = 'k' + x[1..x.size]
x
end
def bar(x)
x[0] = 'k'
x
end
k = 'crazy'
=> "crazy"
foo(k)
=> "krazy"
k
=> "crazy" # !?!?!?!?!
bar(k)
=> "krazy"
k
=> "krazy" # As expected.
------------------- END IRB -------------------------
Can someone explain to me why the method foo() doesn't modify k while
bar() does? I suppose it has something to do with the fact that I'm
using an asignment statement in foo() but modifiying the parameter
"in-place" for bar(). Still, I'm a bit confused.
[author's note: Yes, I know my example isn't very "Rubyish". I just
want to get a better handle on the language.]
Thanks!
-Nathan
discussing how in Ruby everything is an object. He wondered if
everything was call-by-reference, and my knee jerk reaction was yes.
Then I ran the following irb session....
------------------- START IRB -------------------------
def foo(x)
x = 'k' + x[1..x.size]
x
end
def bar(x)
x[0] = 'k'
x
end
k = 'crazy'
=> "crazy"
foo(k)
=> "krazy"
k
=> "crazy" # !?!?!?!?!
bar(k)
=> "krazy"
k
=> "krazy" # As expected.
------------------- END IRB -------------------------
Can someone explain to me why the method foo() doesn't modify k while
bar() does? I suppose it has something to do with the fact that I'm
using an asignment statement in foo() but modifiying the parameter
"in-place" for bar(). Still, I'm a bit confused.
[author's note: Yes, I know my example isn't very "Rubyish". I just
want to get a better handle on the language.]
Thanks!
-Nathan