If you pick up Ruby, you will love it! Currently I am reading the book Metaprogramming Ruby to dive into the depth in Ruby world.
- Open Classes
You can easily add new methods to classes that has already existed, like the following:
class String
def to_alphanumeric
gsub /[^\w\s]/, ''
end
end
Now the String class has a new method ‘to_alphanumeric’. In fact, when you define a class, if it is predefined(like String), Ruby will open the existing class and add your methods. Otherwise, Ruby will create a class for you. This technique is simply called Open Class. So, you can overwrite the existing methods.
- Object and Class Relationship
In Ruby, unlike Java, there is no connection between an object’s class and its instance variables. When you assign values, they just spring into existence in object. Ruby objects hold instance variables and reference to their classes which carry a list of methods. Here is an example:
class A
def hey
@v = "hey"
end
end
obj = A.new
obj.instance_variables # => []
obj.hey
obj.instance_variables # => ["@v"]
You can see that MyClass is just an object. But what MyClass has is instance methods that objects can call. Be careful with this jargon ‘instance method‘. It actually took me some time to understand this. And you can verify by running following code:
Array.instance_methods == [].methods # => true
Array.methods == [].methods #=> false
- Method
When you call a method, Ruby actually does two things:
- Method lookup
- Execute the method
In method lookup, there are concepts receiver and ancestor chain. Receiver is simply the object you call a method on. The ancestor chain is the path from class to its superclass, superclass to superclass’ superclass and so on. Ruby will look at each class’ instance methods along the chain until find the right method. One thing to notice that when you include a module in your class, Ruby creates an anonymous class that wraps the module and add it in the chain. In fact, Object includes module Kernel, that’s why you can call methods like puts, print in your class.
No comments:
Post a Comment