My Ruby Learning

2015/10/24
1. Using ruby meta programming always we can add instance variable & method to specific object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    # Example 2: create a new instance of class Object
    my_object = Object.new

    # create a second instance of class Object
    my_other_object = Object.new

    # define a method on my_object to set the instance variable @my_instance_variable
    def my_object.set_my_variable=(var)
      @my_instance_variable = var
    end

    # define a method on my_object to return value of instance variable @my_instance_variable
    def my_object.get_my_variable
      @my_instance_variable
    end

    my_object.set_my_variable = "Hello"
    my_object.get_my_variable # => Hello

    my_other_object.get_my_variable = "Hello" # => NoMethodError

Post Directory