开发者

Ruby - How to not overwrite instance variables in methods?

Say that we have this class:

class Hello
  def hello
    @hello
  end

  def hello=(hello)
    @hello = hello
  end

  def other_method
    hello = 'hi!'
    ...
  end
end

In this case,

h = Hello.new
h.other_method
puts h.hello

will write 'hi!', due to the interpretation of hello = as self.hello =. Is there a way to avoid this behaviour, giving to the hello = declaration a method-local scope (as, for example , var hello = would do with javascript code)?

EDIT I'm sorry, I was sure I had a problem for this reason! But now I have two other questions!

  1. why hello = is not interpreted as self.hello =??? it is declared as an in开发者_运维知识库stance method...

  2. why, even if I write

...
  def other_method
    self.hello = 'hi!'
  end
end
h = Hello.new
h.other_method
puts h.hello
it returns nil??? now it should be an explicit assignment!

Thank you for the patience, I'm a bit confused! :-/


Actually this will not print hi! because hello = 'hi!' in other_method assigns to a local variable and is not interpreted as self.hello=.

If this is not the behaviour that you're seeing then there must be something else specific to your code that you haven't included in the question.


Answers to the follow up questions:

  1. Within the body of a method identifier = value assigns a local variable (no method lookup is performed (so it's doesn't matter that there's a hello= method. You need the explicit self. to invoke the method.
  2. When you write puts h.hello it prints 'hi!' which is the return value of h.hello but then returns nil which is the return value of puts.


It works for me:

$ irb
irb(main):001:0> class Hello
irb(main):002:1> def hello
irb(main):003:2>   @hello
irb(main):004:2> end
irb(main):005:1> def hello=(hello)
irb(main):006:2>   @hello = hello
irb(main):007:2> end
irb(main):008:1> def other_method
irb(main):009:2>   self.hello = 'hi!'
irb(main):010:2> end
irb(main):011:1> end
=> nil
irb(main):012:0> h = Hello.new
=> #<Hello:0xb746b7cc>
irb(main):013:0> h.other_method
=> "hi!"
irb(main):014:0> puts h.hello
hi!
=> nil
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜