Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ifyouseewendy/4c12777dd8576f3f07cf to your computer and use it in GitHub Desktop.
Save ifyouseewendy/4c12777dd8576f3f07cf to your computer and use it in GitHub Desktop.
Remember, local assignment has precedence over method sending.

There is a weird situation I haven't noticed before:

class Counter
  attr_accessor :processed, :processed_names

  def initialize
    @processed = 0
    @processed_names = []
  end

  def foo
    processed += 1
  end

  def bar
    processed_names << 'a'
  end
end

w = Counter.new;
w.foo # => NoMethodError: undefined method `+' for nil:NilClass`
w.bar # => ['a']

Why the hell?

Local assignment always has precedence over method sending. Assignment happened in w.foo, which not in w.bar.

Check this one:

class Person
  attr_accessor :name

  def foo
    name = 'John'
  end
end

t = Tao.new
t.name # => nil
t.foo  # => 'John'
t.name # => nil

name = 'John' only means a definition of a local variable, which won't send = to name.

@taopier
Copy link

taopier commented Mar 30, 2015

I c. so cute, love u.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment