Issue #17093 has been updated by jeremyevans0 (Jeremy Evans).

Status changed from Feedback to Closed

In Ruby `type = 'default'` only sets a local variable named `type`.  It does not call the `type=` method on self, you need `self.type = 'default'` for that.

See https://ruby-doc.com/docs/ProgrammingRuby/html/tut_expressions.html, specifically the section on "Sidebar: Using Accessors Within a Class".

----------------------------------------
Bug #17093: attr_accessor works strange
https://bugs.ruby-lang.org/issues/17093#change-86857

* Author: mpavel (pavel m)
* Status: Closed
* Priority: Normal
* ruby -v: ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin17]
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN, 2.7: UNKNOWN
----------------------------------------
require 'rubygems'

class A
  def initialize(type:)
    @type = type
  end

  def b
    p type
    p type.nil?
    type = 'default' if type.nil?
    type
  end

  private

  attr_accessor :type
end

RSpec.describe A do
  let(:type) { 'whoaaa' }

  it 'return default' do
    expect(A.new(type: type).b).to eq('default')
  end

  it 'instance variable is "whoaaa"' do
    expect(A.new(type: type).instance_variable_get(:@type)).to eq(type)
  end
end

all tests green

output
A
"whoaaa"
false
  return default
  instance variable is "whoaaa"



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>