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?

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