15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

518<br />

Creating Objects<br />

When defining a hash with multiple lines, use square brackets.<br />

To retrieve data from a hash, identify the hash name and a key value, such as<br />

puts hashname[“key”]<br />

So if you wanted to retrieve data stored under the key “pi”, you could do<br />

the following:<br />

hashname = Hash.new<br />

hashname[“pi”] = 3.14<br />

puts hashname[“pi”]<br />

The first line creates a hash data structure. The second line stores the value<br />

3.14 into the hash using the key “pi”. The third line prints out the value<br />

identified by the “pi” key in the hash data structure.<br />

Creating Objects<br />

Ruby supports object-oriented <strong>programming</strong>. To create an object, you must<br />

define a class, which specifies the properties and methods, such as<br />

class Classname<br />

def propertyname<br />

@propertyname<br />

end<br />

def propertyname=(propertyname)<br />

@propertyname = propertyname<br />

end<br />

def methodname(parameter list)<br />

commands<br />

end<br />

end<br />

To create an object, you must use the following syntax:<br />

objectname = Classname.new<br />

To assign a value to an object’s property, you need to specify the object<br />

name and the property you want to use, such as<br />

objectname.propertyname = value

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!