Project

General

Profile

Actions

Bug #17093

closed

attr_accessor works strange

Bug #17093: attr_accessor works strange

Added by mpavel (pavel m) over 5 years ago. Updated over 5 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)

Updated by jeremyevans0 (Jeremy Evans) over 5 years ago Actions #1 [ruby-core:99406]

  • 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 5 years ago Actions #2 [ruby-core:99408]

seriously?
attr_accesor doesnot provide value?

Updated by jeremyevans0 (Jeremy Evans) over 5 years ago Actions #3 [ruby-core:99409]

  • 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 5 years ago Actions #4 [ruby-core:99412]

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 5 years ago Actions #5 [ruby-core:99414]

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

Updated by nobu (Nobuyoshi Nakada) over 5 years ago Actions #6

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

Updated by nobu (Nobuyoshi Nakada) over 5 years ago Actions #7

  • Has duplicate Bug #17096: attr_accessor doesnt work added

Updated by mpavel (pavel m) over 5 years ago Actions #8 [ruby-core:99416]

are you try this solution?

if type.nil? type = 'default' end 

just test it )

Actions

Also available in: PDF Atom