2

Why does ruby define a local variable for a, even if the code block does never run?

class Something
  attr_reader :a

  def call
    puts "#{defined?(a)}"
    if false
      a = 1
    end
    puts "#{defined?(a)}"
  end
end

Something.new.call
# method
# local-variable

I would expect a to be a method throughout call. It seems that ruby detects a potentially assignment and creates the local var. Why?

Pascal
  • 8,464
  • 1
  • 20
  • 31
  • 5
    See [Local Variables and Methods](https://ruby-doc.org/core-3.0.2/doc/syntax/assignment_rdoc.html#label-Local+Variables+and+Methods): _"The local variable is created when the parser encounters the assignment, not when the assignment occurs"_ – Stefan Sep 07 '21 at 16:49
  • Thanks for the pointer. I was more wondering why the local var is created at parse time? I just had to debug a weird bug that happened because of this in some old code :-) – Pascal Sep 07 '21 at 17:14
  • 3
    It's the parser's job to create variables every time it sees a potential assignment. Whether an actual value is assigned to this variable is decided (much) later when actually running the program. However, at this later stage, the VM can be sure that there is enough allocated memory to hold a value for the variable if a value is assigned to it. – Holger Just Sep 07 '21 at 19:50

0 Answers0