[prev in list] [next in list] [prev in thread] [next in thread]
List: ruby-talk
Subject: Re: Why nil
From: Stefano Crocco <stefano.crocco () alice ! it>
Date: 2018-07-04 12:41:30
Message-ID: 1906617.j9CD53PHao () linux
[Download RAW message or body]
On mercoledì 4 luglio 2018 14:06:39 CEST dade wrote:
> Hello, let's look at an example
>
> class A
> attr_accessor :a
>
> def initialize(a)
> @a = a
> end
>
> def method1(val)
> a = val
> end
>
> def method2(val)
> a = a + val
> end
> end
>
> a = A.new(1)
> a.method1(2) #=> 3
> a.method2(2) #=> undefined method `+' for nil:NilClass
>
> Why the second a is nil?
>
>
>
> dade.
Why should it be something else than nil? inside method2, a is a local
variable. To execute the line a = a + val, ruby first compute the right hand
side of the expression, which is a + val. Since you haven't given a value to
the variable a, it is implicitly set to nil. Ruby then tries to sum nil to
value and it fails.
I think that you expected method1 and method2 to call the accessor methods,
but this is not what happens. When ruby sees a = ..., it assumes that a is a
local variable, and doesn't even notice that there are methods called "a" and
"a=". To avoid this and have the accessor methods called from method1 and
method2, you have to explicitly tell ruby those "a" are methods by calling
them with the dot notation (using self as receiver):
class A
attr_accessor :a
def initialize(a)
@a = a
end
def method1(val)
self.a = val
end
def method2(val)
self.a = a + val
end
end
I hope this helps
Stefano
Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic