Ruby - Get Data from an Object

Introduction

Consider the following code:

def get_name 
     return @myname 
end 

The return keyword here is optional.

When it is omitted, Ruby methods will return the last expression evaluated.

Here is the finished class definition:

Demo

class Dog    
     def set_name( aName ) 
        @myname = aName # from   w w  w . j  a v a  2s  . c o m
     end 

     def get_name 
        return @myname 
     end 

     def talk 
        return 'woof!' 
     end 
end 

mydog = Dog.new 
mydog.set_name( 'Fido' ) 
puts(mydog.get_name) 
puts(mydog.talk)

Result

Related Topic