Forum: Ruby Struct class

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ves P. (Guest)
on 2008-12-04 01:33
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
James G. (Guest)
on 2008-12-04 02:36
(Received via mailing list)
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
Avdi G. (Guest)
on 2008-12-04 04:51
(Received via mailing list)
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
This topic is locked and can not be replied to.