3 ms·
"Passing by reference" section is wrong about Ruby (not sure about Python). Ruby passes everything by reference, it's only that integers are immutable so that t
by jablan 15y ago
"Passing by reference" section is wrong about Ruby (not sure about Python). Ruby passes everything by reference, it's only that integers are immutable so that the function can't alter them. Strings, though, are mutable:
def foo s
s.concat 'foo'
end
a = 'bar'
foo a
a
# => "barfoo"
- rplnt 15y agoIn python, strings are immutable as well.
- joesb 15y agoNiether Ruby or Python do "pass by reference". They both do "pass reference by value". Which is a big difference.
- sciurus 15y agoNot exactly. Let's tweak your example to create a new object in your method. def foo s s = 'foo' end a = 'bar' foo a puts a # => bar The assignment in the method doesn't change the object you "passed" in. Rather than passing by reference, think of Ruby as passing the value of a reference. For more examples and explanation, see http://khelll.com/blog/ruby/ruby-pass-by-value-or-by-reference/ http://khelll.com/blog/ruby/ruby-pass-by-value-or-by-referen...
- vidarh 15y agoWell, integers are immutable (and conceptually a singleton per value) unless you override stuff in FixNum and add instance variables. Here's an evil example that works at least in MRI 1.8.6: class Fixnum alias :realplus :+ def + b @a ||= 0 @a = @a.realplus(b) self.realplus(@a) end end The integer value itself is immutable, though. Of course all hell will break loose and adding instance variables in certain classes like Fixnum will be extra slow (as if there aren't enough other reasons not to), since MRI uses type-tagging for Fixnum, Symbol and a few others, and so since they're not "real" objects, if you do anything that requires one, it creates one that's stored in a hash table.