The following code works fine (windows XP, Ruby 1.86)
Card = Struct.new(:rank, :suit)
class Card
def to_s
"#{rank} of #{suit}"
end
end
c = Card.new(2, "hearts")
c.rank
···
2
#####################################################
The following doesn't work:
Card = Struct.new(:rank, :suit)
class Card
attr_reader :rank, :suit
def to_s
"#{rank} of #{suit}"
end
end
c = Card.new(2, "hearts")
c.rank
nil
####################################
Any ideas why?
TIA,
ves
--
Posted via http://www.ruby-forum.com/\.
Sure.
attr_reader() builds methods that shadow an instance variable but Struct cheats and doesn't store member data in instance variables. Thus you are replacing the readers generated by Struct with methods that look for the data in the wrong place.
I cover this and more details about Struct in the following blog post, in case you are interested:
Hope that helps.
James Edward Gray II
···
On Dec 3, 2008, at 5:28 PM, Ves Pasian wrote:
The following doesn't work:
Card = Struct.new(:rank, :suit)
class Card
attr_reader :rank, :suit
def to_s
"#{rank} of #{suit}"
end
end
c = Card.new(2, "hearts")
c.rank
nil
####################################
Any ideas why?
...which is a terrific article, I might add, and well worth reading.
···
On Wed, Dec 3, 2008 at 7:29 PM, James Gray <james@grayproductions.net> wrote:
I cover this and more details about Struct in the following blog post, in
case you are interested:
Gray Soft / Not Found
--
Avdi
Home: http://avdi.org
Developer Blog: Avdi Grimm, Code Cleric
Twitter: http://twitter.com/avdi
Journal: http://avdi.livejournal.com