# comments begin with pound
# define a function
def my_function( param1 , param2=5 )
return param1*param2
end
# call a function
puts "functions:"
puts my_function( 3 , 10 ) #=> nil
puts my_function( 3 ) #=> nil
# define a class
class MyClass
@@class_level_variable = 3 #double @ indicates class variable
#this is a callback, it gets invoked when new instance is made
def initialize( value )
@instance_variable = value #single @ indicates instance variable
end
def value
return @instance_variable
end
#to invoke: my_instance_of_MyClass.value = 9
def value=(param)
@instance_variable = param
end
def use_both_variables
@@class_level_variable * @instance_variable
end
end
#using a class
puts "\n\nclasses / methods:"
my_instance_of_MyClass = MyClass.new(7) #construct the object (note: Ruby has garbage collector)
puts my_instance_of_MyClass.value #=> 7
puts my_instance_of_MyClass.use_both_variables #=> 21
local_variable = 8 #just start using it, like this
my_instance_of_MyClass.value = local_variable * 2
puts my_instance_of_MyClass.value #=> 16
puts my_instance_of_MyClass.use_both_variables #=> 48