Hi,
I am new to Ruby, just start reading the pickaxe.
Here I have a question regarding passing parameters by value or
reference. Hence everything is an object and the book mentioned for
a="abc"; b=a just created a new reference to "abc", I guess it applies
to everything is an object (could I be wrong here?).
Seems it is not the case for Fixnum.
#sample code from pickaxe
def n_times(thing)
lambda {|n| thing * n}
end
=> nil
#Fixnum and String
a=b=23
=> 23
c=d="abc"
=> "abc"
#c, d and 'thing' are reference to same thing, just as the book said
p2=n_times(c)
=> #<Proc:0x802b7980@(irb):18 (lambda)>
p2.call(3)
=> "abcabcabc"
c.insert(-1,'d'); d.insert(-1, 'e')
=> "abcde"
p2.call(3)
=> "abcdeabcdeabcde"
#not apply to Fixnum???
p1=n_times(a)
=> #<Proc:0x802c0bc0@(irb):18 (lambda)>
p1.call(3)
=> 69
a=a+1; b=b+1
=> 24
p1.call(3)
=> 69
At first, seems to me when pass Fixnum, Ruby makes a copy. But further
dig seems it was the assignment:
a=b=10
=> 10
p a.object_id; p b.object_id
21
21
=> 21
a+=1
=> 11
p a; p b
11
10
=> 10
# object_id changed after assignment!
p a.object_id; p b.object_id
23
21
=> 21
Why Fixnum behaves different from String? Is the number class (e.g.
Fixnum, Float) the only one in Ruby core that behave like this? A little
bit confusing here
a=b=10
=> 10
p a.object_id; p b.object_id
21
21
=> 21
a=a<<1
=> 20
# a was changed!
p a.object_id; p b.object_id
41
21
=> 21
c=d="abc"
=> "abc"
p c.object_id; p d.object_id
-1072646678
-1072646678
=> -1072646678
c=c << "d"
=> "abcd"
# same operator << (ok, different operation for Fixnum)
# didn't change the obj id for String
p c.object_id; p d.object_id
-1072646678
-1072646678
=> -1072646678
p d
"abcd"
Thanks for reading. I appreciate any help/comment.
J.T