Strange ruby ​​attr_accessor behavior

I have this code block:

class CallMe
  attr_accessor :a, :b, :c

  def self.start(*args)
     self.new(*args).get_answer
  end

  def initialize(a,b,c)
    @a = a
    @b = b
    @c = c
  end

  def get_answer 
    if c
      b = nil
    else
      return b 
    end
   end
end
answer = CallMe.start(1,2,nil)

Why, when I run it in irb, I always get answer = nil, even the logical case is to get b value equal to 2

+4
source share
2 answers

Variable Hoisting is used in many languages. For Ruby, this is described in the official documentation :

A local variable is created when the parser encounters an assignment, and not when an assignment occurs

, get_answer b c. b nil . get_answer b, nil.

:

def get_answer
  c ? self.b = nil : b
end
+3

, if b b = nil. Ruby , :b b. , - if.

if c
  b = nil
else
  return b
end

# to 
if c
  # b = nil
  # or
  self.b = nil
else
  return b

, , .

0
source

Source: https://habr.com/ru/post/1681267/


All Articles