Interpretation as a local variable overrides method name?

后端 未结 3 1782
北荒
北荒 2020-12-11 07:23

As in this question, when a local variable not defined is used within its own assignment, it is evaluated to nil.

x = x # => nil 
         


        
3条回答
  •  [愿得一人]
    2020-12-11 07:30

    I think in your case it's because it's what's expected :P

    1.9.3-p194 :001 > {}.instance_eval{a=1}
     => 1 
    1.9.3-p194 :002 > {}.instance_eval{a}     
    NameError: undefined local variable or method `a' for {}:Hash
        from (irb):2:in `block in irb_binding'
        from (irb):2:in `instance_eval'
        from (irb):2
        from /Users/rafael/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `
    '

    Instance eval evaluates code at instance level so each hash you are declaring is different. If you want to return keys this works

    1.9.3-p194 :003 > {}.instance_eval{keys = self.keys
    1.9.3-p194 :004?>   keys = keys}
     => [] 
    

提交回复
热议问题