Project

General

Profile

Actions

Bug #17093

closed

attr_accessor works strange

Added by mpavel (pavel m) over 3 years ago. Updated over 3 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin17]
[ruby-core:99405]

Description

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"

Related issues 1 (0 open1 closed)

Has duplicate Ruby master - Bug #17096: attr_accessor doesnt workRejectedActions

Updated by jeremyevans0 (Jeremy Evans) over 3 years ago

  • Status changed from Open to Feedback

Do you expect the type = 'default' in b to set the @type instance variable to 'default'? If so, that doesn't work, you need to use self.type = instead of type =. If not, can you provide an explanation of what behavior you are expecting?

Updated by mpavel (pavel m) over 3 years ago

seriously?
attr_accesor doesnot provide value?

Updated by jeremyevans0 (Jeremy Evans) over 3 years ago

  • 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".

Updated by mpavel (pavel m) over 3 years ago

you doesnt see "if type.nil?" its local variable?
p type.nil? return false
next "if type.nil?" return true and "type = 'default'" will work
why?

Updated by Hanmac (Hans Mackowiak) over 3 years ago

This:

if type.nil?
 type = 'default'
end

is different from this:

type = 'default' if type.nil?

because of the lexical reading, it reads the setting of local variable first and now assumes that type is local variable in this case

Actions #6

Updated by nobu (Nobuyoshi Nakada) over 3 years ago

  • Description updated (diff)
  • Status changed from Closed to Rejected
Actions #7

Updated by nobu (Nobuyoshi Nakada) over 3 years ago

  • Has duplicate Bug #17096: attr_accessor doesnt work added

Updated by mpavel (pavel m) over 3 years ago

are you try this solution?

if type.nil?
 type = 'default'
end

just test it )

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0