Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Struct method can't set struct member [duplicate]

Tags:

ruby

An example will explain the question:

Val = Struct.new(:value) do
  def inc 
    p value
    value = value + 1 
  end
end

v = Val.new(1)
v.inc

The output will be:

1
undefined method `+' for nil:NilClass (NoMethodError)

Why do I get this error when value is clearly not nil? Is there a way to make this work?

like image 460
Jonah Avatar asked Aug 29 '26 21:08

Jonah


2 Answers

Val = Struct.new(:value) do
  def inc 
    p value # here it still prints 1

    # but here you REDEFINED what value is. It is now a local variable!
    # Also its initial value is nil, hence the error you're getting.
    value = value + 1 

    # should have used this instead, to reference the method
    self.value = value + 1
  end
end
like image 73
Sergio Tulentsev Avatar answered Sep 01 '26 16:09

Sergio Tulentsev


Clarification on Sergio's answer.

Within inc's definition, there is initially no variable value, and what is called by p value is the method value, which returns 1.

Then in line value = value + 1, at the point when value = has been parsed, a local variable value is created and is initialized to nil. Even though value + 1 is evaluated prior to assignment of its value into the newly created value, the initialization of value takes place first. So, when value + 1 is to be evaluated, there already is a local variable value, which has priority to be called over the method value. And this value is nil.

like image 43
sawa Avatar answered Sep 01 '26 15:09

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!