Ruby basic notes - Classes, Constructors, and Symbols

Ruby

**Classes are like factories that generates objects - i.e. instances of that class**

**An object is a combination of „state“ or attributes (e.g. quantity and product ID) and methods that use that state (e.g. calculate total cost of the line item).**

A Constructor is a special method for a class.  The standard constructor is ().new.

summer_dress = LineItem.new

summer_dress.price = 5.00

summer_dress.quantity = 1

summer_dress.id = 443213

How do Methods work?

When you call a method on an object, you trigger a message to the object.  The message contains the method’s name, along with any parameters the method may need.  When an object receives the message, it looks into its own class for a corresponding method.  

 

A Symbol in Rails ( :symbol ) is the simplest Ruby object you an create.  It’s just a name with an ID.  It’s printed as a colon followed by a name.  Symbols are useful because the name is just one object, with just one ID.  Whereas every string, even if its identical, has a new ID.  So symbols save memory. 

Ruby keeps a Symbol Table.  You can see all the Symbols (really, names) that Ruby uses by calling Symbol.all_symbols. 

 

Symbols don’t contain values or objects like variables do.  Instead, they’re used as a consistent name within code.  This is why they’re sort of like constants

You can assign a symbol to a variable, just like you can assign a string to a variable:

name = :henry

name = “henry“

The :henry symbol will simply be more efficient than the string “henry“ because every additional use of the :henry symbol will use the identical ID.  

Rails makes use of symbols as keys for hash values. 

instruments = 

{

:cello  =>  ‚string‘,

:clarinet   =>  ‚woodwind‘,

:drum  =>  ‚percussion,,

: oboe  =>  ,woodwind’

}

After Ruby 1.9, they made a special syntax (what Alec told me about on our run!), for assigning symbols as keys in hashes:

instruments = 

{

cello: ’string’,

clarinet: ’woodwind’,

drum: ’percussion’,

oboe: ’woodwind’,

}

 

Interestingly, even if the symbol is used in different situations (e.g., if Fred is  in different contexts the name of a method, the name of a constant, the name of a class, the Symbol :Fred will actually be the same object in all three contexts.

In a way, you can think of :id as the „name of the variable“ and plain id as the value of the variable. 

Symbols are a great, efficient way to attach a human-readable name onto something.  But if the data itself is important you should use a string.

Here’s a great Rails example.  Rails uses symbols in routes and links.  

link_to(“View Article“), :controller => “articles“, :action => “show“

 

I’m not sure I entirely understand this example.  Is :controller just actually a name?

| Back

Footerfull