Reputation: 12540
This applies also to attr_writer
and attr_accessor
.
I've been playing with some simple Ruby code recently and the following snippet does not work in all environments I've run it:
class Human
attr_reader :name
def initialize(name)
@name = name
end
end
hank = Human.new("Hank")
hank.name
This should output "Hank", which it does in my command line irb. In Textmate2 and Aptana Studio 3, nothing outputs when I run this code. All three work as expected if I explicitly define the reader:
def name
puts @name
end
When I play in the Aptana terminal and my usual terminal and type:
$ ruby -v
They both appear to use the same version: ruby 2.0.0p451. What's going on?
Upvotes: 0
Views: 34
Reputation: 1511
attr_reader just doesn't do what you think it does.
try
puts hank.name
rather than
hank.name
and you'll see the output. irb is a special case, it shows you the return value of the last statement executed. ruby on its own won't do that, it only prints things you explicitly tell it to print.
Upvotes: 3