Hacker News new | past | comments | ask | show | jobs | submit login

"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"



Well, 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.


Not 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-referen...


In python, strings are immutable as well.


Niether Ruby or Python do "pass by reference".

They both do "pass reference by value". Which is a big difference.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: