Bug #17093
closedattr_accessor works strange
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"
Updated by jeremyevans0 (Jeremy Evans) over 4 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 4 years ago
seriously?
attr_accesor doesnot provide value?
Updated by jeremyevans0 (Jeremy Evans) over 4 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 4 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 4 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
Updated by nobu (Nobuyoshi Nakada) over 4 years ago
- Description updated (diff)
- Status changed from Closed to Rejected
Updated by nobu (Nobuyoshi Nakada) over 4 years ago
- Has duplicate Bug #17096: attr_accessor doesnt work added
Updated by mpavel (pavel m) over 4 years ago
are you try this solution?
if type.nil?
type = 'default'
end
just test it )