Struct class


#1

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


#2

On Wed, Dec 3, 2008 at 7:29 PM, James G. removed_email_address@domain.invalid
wrote:

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

…which is a terrific article, I might add, and well worth reading.


Avdi

Home: http://avdi.org
Developer Blog: http://avdi.org/devblog/
Twitter: http://twitter.com/avdi
Journal: http://avdi.livejournal.com


#3

On Dec 3, 2008, at 5:28 PM, Ves P. wrote:

c = Card.new(2, “hearts”)
c.rank

nil

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

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 G. II