[ create a new paste ] login | about

Link: http://codepad.org/DpIxOR3d    [ raw code | output | fork | 1 comment ]

joshua_cheek - Ruby, pasted on Oct 25:
# 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


Output:
1
2
3
4
5
6
7
8
9
10
functions:
30
15


classes / methods:
7
21
16
48


Create a new paste based on this one


Comments:
posted by joshua_cheek on Nov 15
A few simple Ruby things to know.
reply