Why Use Symbols?

Some methods in the Ruby class library specify symbols as arguments. Naturally, if you need to call those methods, you are obliged to pass symbols to them. Other than in those cases, however, there is no absolute requirement to use symbols in your own programming. For many Ruby programmers, the “conventional” data types such as strings and integers are perfectly sufficient. However, many Ruby programmers do like to use symbols as the keys into hashes. When you look at the Rails framework in Chapter 19, for example, you will see examples similar to the following:

{ :text => "Hello world" }

Symbols do have a special place in “dynamic” programming, however. For example, a Ruby program is able to create a new method at runtime by calling, within the scope of a certain class, define_method with a symbol representing the method to be defined and a block representing the code of the method:

add_method.rb

class Array
    define_method( :aNewMethod, lambda{
        |*args| puts( args.inspect)
    } )
end

After the previous code executes, the Array class will have gained a method named aNewMethod. You can verify this by calling method_defined? with a symbol representing the method name:

Array.method_defined?( :aNewMethod )   #=> true

And, of course, you can call the method itself:

[].aNewMethod( 1,2,3     #=> [1,2,3]

You can remove an existing method at runtime in a similar way by calling remove_method inside a class with a symbol providing the name of the method to be removed:

class Array
    remove_method( :aNewMethod )
end

Dynamic programming is invaluable in applications that need to modify the behavior of the Ruby program while that program is still executing. Dynamic programming is widely used in the Rails framework, for example, and it is discussed in depth in the final chapter of this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.12.156