Struct class

V

Ves Pasian

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
#####################################################

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
####################################

Any ideas why?
TIA,
ves
 
J

James Gray

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

####################################

Any ideas why?

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:

http://blog.grayproductions.net/articles/all_about_struct

Hope that helps.

James Edward Gray II
 

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

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,218
Latest member
JolieDenha

Latest Threads

Top