Shiva Kumar 's Blog

Start small,Think Big

Struct in Ruby

Struct is a simple way to create a class with number of attributes without explicitly creating a class

Syntax to create a class using struct

1.9.2p290 :004 > Struct.new("User",:name,:email)

Where User is the class name.Name and email are the attributes of the class where passing it on the fly.
So when you want to create new user all you do is

1.9.2p290 :006 > user=Struct::User.new("Shiva","shiva@example.com")
=> #<struct Struct::User name="Shiva", email="shiva@example.com">

This basically create a new user with name shiva and email
shiva@example.com.The order of passing the attribute is very important

1.9.2p290 :007 > user.name
=> "Shiva"
1.9.2p290 :008 > user.email
=> "shiva@example.com"

There is cool trick by Steve Klabnik to use struct .Using struct to inherit from

1.9.2p290 :012 > class User < Struct.new(:name,:email)
1.9.2p290 :013?> end
=> nil
1.9.2p290 :016 > user=User.new("shiva","shiva@example.com")
=> #<struct User name="shiva", email="shiva@example.com">
1.9.2p290 :017 > user.name
=> "shiva"

Because Struct.new(:name,:email) gives you class .And you can inherit it from like any other class

1.9.2p290 :025 > Struct.new(:name,:email)
=> #<Class:0x000001008cae78>

, , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">