title: Strangeness in Ruby
body: <p>I've got a simple if statement that is behaving very strangely. When I assign a value to an <code>attr_accessor</code> within the if statement that it wipes out the value. Here's a concise example that demonstrates the issue.</p>
  
  <pre><code>class FName
    attr_accessor :name
    attr_accessor :file_ext
  
    def full_name
      puts "initial file_ext value: #{file_ext}"
      if file_ext.nil?
        file_ext = ".default"
      end
      puts "new file_ext value: #{file_ext}"
      "#{name}#{file_ext}"
    end
  end
  
  f = FName.new
  f.name = "foo"
  f.file_ext = ".txt"
  puts f.full_name
  </code></pre>
  
  <p>This outputs the following:</p>
  
  <pre><code>initial file_ext value: .txt
  new file_ext value:
  foo
  </code></pre>
  
  <p>Which is not at all what you'd expect. Anyone have any idea what's going on here?</p>
  
  <p>Note that I can reproduce this problem in both Ruby 2.0.0-p247 and Ruby 2.1.1_1. Also note that if I remove the line <code>file_ext = ".wrong"</code> then the code sample behaves as expected when file_ext is not nil, but of course I then don't have a way to provide a default value when file_ext is nil.</p>
  
  <p>I've tried putting <code>puts</code> statements into the if block, and (as expected) they print nothing. When I remove the line <code>f.file_ext = ".txt"</code> then I get the output:</p>
  
  <pre><code>initial file_ext value:
  new file_ext value: .default
  foo.default
  </code></pre>
  
  <p>One last note: I'm hoping to provide the default value lazily like this because in my real code the value is computed and I'm hoping to avoid the computation unless necessary.</p>
  
  <p>Hopefully someone out there can tell my why this is happening!</p>