Using attr_writer?

J

Joe

I'm confused about attr_writer. I thought it worked like this:

class Foo
attr_writer :bar

def do_stuff
puts @bar
end
end

foo = Foo.new
foo.bar = 'baz'
foo.do_stuff # gives nil error

Can somebody enlighten me? :)

Thanks,
Joe
 
M

Marcin Mielżyński

Joe said:
I'm confused about attr_writer. I thought it worked like this:

class Foo
attr_writer :bar

def do_stuff
puts @bar
end
end

foo = Foo.new
foo.bar = 'baz'
foo.do_stuff # gives nil error

Can somebody enlighten me? :)

Thanks,
Joe

puts returns nil


lopex
 
E

E. Saynatkari

Joe said:
I'm confused about attr_writer. I thought it worked like this:

class Foo
attr_writer :bar

def do_stuff
puts @bar
end
end

foo = Foo.new
foo.bar = 'baz'
foo.do_stuff # gives nil error

Can somebody enlighten me? :)

This is perfectly valid. If this is not your actual code,
could you post that instead? It might be something else
entirely.
Thanks,
Joe


E
 
H

Huw Collingbourne

Curious. I just copied, pasted and ran your code. It produces the string
'baz'. I don't get an error.

best wishes
Huw Collingbourne
================================
Bitwise Magazine
www.bitwisemag.com
Dark Neon Ltd.
================================
 
J

Jeff McNeil

Are you running it in irb? As someone else mentioned.. you'll get a
"nil" message as that's the return value of puts.

-Jeff

Curious. I just copied, pasted and ran your code. It produces the
string
'baz'. I don't get an error.

best wishes
Huw Collingbourne
================================
Bitwise Magazine
www.bitwisemag.com
Dark Neon Ltd.
================================
 
J

Joe

Turns out I had a bug elsewhere in my code and it does in fact work as
advertised. Thanks for the responses. :)

Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top