Object Oriented Programming in ruby - ruby

Is method an object in Ruby? My friend asked me this question.I read about this in website.But still I didn't understand it.Can anyone help me?

There seems to be a confusion here due to ambiguity of the term method. Method in the most ordinary sense is not an object. In the following:
"foo".upcase
the method upcase is applied to an object "foo", but upcase is not an object, as can be seen by the fact that it cannot stand alone:
upcase # => error
(Do not confuse this with when it can be considered that the receiver is omitted).
However, there is a class Method, whose instances correspond to methods, and are objects. They may also be called methods, but that is not the normal usage of the term method.

No, they are not.
Methods themselves are a language structure of Ruby, and they are not objects. But there is a class Method, whose instances represent methods, and can be called using Method#call.
Also, there is another kind of instances - instances of class UnboundMethod, which represent methods that are detached from specific objects. They can't be called directly, but can be used in many different ways.
If you are looking for something like Javascript's functions, then procs and lambdas are what you want.

Related

On which object/class does DelegateClass and similar methods live?

Sorry for the poor title, but I'm a bit lost.
I'm trying to figure out on which object/class live methods such as DelegateClass and what is the term for these types of methods. I'm reading Metaprogramming Ruby and, in the book, these methods are generically called Mimic Methods, but searching the internet for this gives all kinds of results, so I'm wondering if there's a better name for them.
I've checked the source code of DelegateClass and I assumed that it was added to Object, but it's not there. I can see the the classes Delegator and SimpleDelegator, which are in the same rb file, are added as constants (although I'm not sure how they are added).
Thanks!
Just found the answer. It's a private method in Object
ruby-1.9.2-p290 :033 > Object.private_instance_methods(false).grep /Dele/
=> [:DelegateClass]
edit
I found out that what I needed to understand is What is the current class? in a given context.
Look closer at the file.
def DelegateClass(superclass)
klass = Class.new(Delegator)
...
and use
method(:DelegateClass).owner
to find the class where it sits. As mentioned in the comments private instance methods on Module contain anything defined on Object.
So no, DelegateClass() is not a special method in any way except for being called in uppercase (which makes it look like a constant). It just returns an anonymous class created on-the-spot that can be inherited from.

Do rubyists reference accessors from mixins?

Is it considered bad practice to reference accessors on the extended object from within a mixin method? A simplistic example:
module WindInstrument
def play
mouthpiece.blow #requires a mouthpiece
end
end
class Saxophone
attr_reader :mouthpiece
def initialize
#mouthpiece = Mouthpiece.new
end
include WindInstrument
end
Saxophone.new.play
In this case, I would actually just move the requirement for a mouthpiece directly to the WindInstrument module, but what about in a more complex scenario, where it really makes sense for the accessor to live on the extended object? Is this just an issue of an inappropriate separation of concerns?
Mixins feel useful for adding encapsulated behavior that doesn't require knowledge of the extended object's state. In fact, my gut tells me that a mixin shouldn't have knowledge of any state, whatsoever. If it needs knowledge of state, I would typically fall back to one of two choices:
Put the state in a class, and add it through composition, instead of through the inheritance hierarchy. My issue with this is that I know rubyists out there are creating mixins that access state, which makes for more readable, if less intuitive (to me) design.
Pass the mouthpiece as a parameter to the module. Even I can tell that this seems to muddy the design, and feels like an abomination in the ruby worldview.
Does this code bother anyone else? I know there are a lot of smart people using ruby out there, so I assume the problem is mine. What am I missing? Do I just need to chill out? What would you do?
I think it's the same as in monkey-patching: it's ok to do it, but you have to make sure that there are no alternatives first (ie. You can't modify the classes using your interface) and second, you must be very explicit about it (make sure that the docs, the comments and the interface mention that this our that method is required and will be invoked) and throw a useful error message if it isn't
Ruby's accessors are interfaces, not implementation.
For example, if you call person.height_in_feet=, you don't know what units the height is actually implemented in as an instance variable. It could be metres, feet, or cubits.
One real-life example of mixins using an accessor is the Enumerable module. Although I don't include this module in any classes I create, I'm happy with what it does. It gives you convenient methods like map and each_with_index, while staying DRY - there's only one implementation of what objects you'd access with all of the methods of the "mixee", and there's only one definition of what map does, for any object that uses Enumerable.

Good explanation of ruby object model -- mainly, 'classes are objects'?

I am studying the ruby object model and have some questions. I understand the idea that an object only stores instance variables, and methods are stored in the class, which an object has a reference to. I also understand the idea of 'self' -- what it is, how it changes, etc.
However, what I don't understand is the notion that 'classes are objects.' Is there a good, intuitive explanation anywhere?
(BTW: I'm using Ruby Object Model and Metaprogramming and Metaprogramming Ruby as my two resources. If anybody can suggest something else, that would be helpful.)
Thanks.
It means precisely what it sounds like — classes are objects. Specifically, they are instances of the class Class, which is itself a subclass of the class Module, which in turn is a subclass of Object, just like every other class in Ruby. Like any other object in Ruby, a class can respond to messages, have its own instance variables, etc.
As a practical example, let's take private.
class Person
attr_accessor :name, :height
private
attr_accessor :weight
end
This gives instances of Person public methods to access the person's name and height, but the accessors for the person's weight are private. BUTBUTBUT — rather than being a keyword like in most languages, private is an ordinary method of the Module class. If we wanted, we could redefine it to do something different for a particular class hierarchy.
class RichardStallman
def self.private(*args)
puts "NO! INFORMATION WAS MEANT TO BE FREE!"
end
end
Here's my shot at one.
In Ruby, classes are objects. Usually they have class Class. For example, let's consider the class Foo.
class Foo
end
Doubtless you've seen this before, and it's not terribly exciting. But we could also have defined Foo this way:
Foo = Class.new
Just as you'd create a new Foo by calling Foo.new, you can create a new Class by calling Class.new. Then you give that class the name Foo by assigning it, just like any other variable. That's all there is to it.
The notion of "classes are objects" ( as I understand it ) implies that anything you can do with an object, you can do it with a class.
This differs from other programming languages where the class and the class definition are special artifacts different from objects and often unaccessible to the runtime.
For instance in Ruby, you can modify any object at runtime, since classes are also objects you can modify the class it self and add methods at runtime, delete methods, or add and delete attributes at runtime.
For instance:
$ irb
>> x = Object.new
=> #<Object:0x1011ce560>
>> x.to_s
=> "#<Object:0x1011ce560>"
>> undef to_s
=> nil
>> x.to_s
NoMethodError: undefined method `to_s' for #<Object:0x1011ce560>
from (irb):4
>>
That's not possible on other programming languages where a distinction between objects and classes is made.
note: Probably you should understand basic Ruby concepts before going to meta programming as it may be confusing, that what I would do.
Look at this article, you may find it helpful:
The Ruby Object Model - Structure and Semantics
Personally I learned a lot about the Ruby object model by reading about the Smalltalk one (e.g. in the Squeak documentation). And depending on how fluent you are in C, the MRI sources are quite approachable and yield the most definite answers.
When you think of it, it's completely logical for new to be a function, right? A function which creates and returns a new object. (Unlike most of other languages where new is some kind of operator or a language construct.)
Pushing it further, even more logical for this function new is that it should be a method, if we are talking about an OO language. Whose method? A method of an object, just a little bit different sort of an object that we can call "class".
So, looking it that way, classes are just special kinds of objects, objects that, among other peculiarities, have method new and know how to create other objects based on their own image.
what I don't understand is the notion that 'classes are objects.' Is there a good, intuitive explanation anywhere?
An answer to SO thread `Visual representation of Ruby Object Model' links to an excellent video on the subject.

Ruby - Array method confusion

we can call the Array method in the top level like this
Array(something)
that makes sense to me, it's a method call without explicit receiver, and self, which is main in this case, is inserted at the front of the method call. But isn't it that this is equivalent to :
Kernel.Array(something)
this doesn't make sense to me. Since in the first case, the object main is of class Object, which got Kernel module mixed in, thus have the Array method. But in the second case, we are calling the Array method on the Kernel module object itself, rather than main object, didn't they are NOT the same thing?
sorry for my bad english.
Kernel.Array is what is known as a module function. Other examples of module functions include Math.sin, and Math.hypot and so on.
A module function is a method that is both a class method on the module and also a private instance method. When you invoke Array() at the top-level you are invoking it as a private instance method of the main object. When you invoke it through Kernel.Array() you are invoking it as a class method on Kernel. They are the same method.
To learn more, read up on the module_function method in rubydocs: http://www.ruby-doc.org/core/classes/Module.html#M001642
class Object mixed-in module Kernel, but Kernel is an instance of Object. So Kernel "module" methods - is it's instance methods.
What's confusing you is the difference between class and instance methods.
Class methods don't have an explicit receiver, and thus no self to access other fields with. They just... are.
Generally instance methods are used to query or manipulate the attributes of a given object, whereas the class methods are "helper" or "factory" methods that provide some functionality associated with or especially useful for a certain kind of class, but not dependent on actual live instances (objects) of that class.
Not sure about Ruby, but Java has (for example) a whole class, Math that contains nothing but instance methods like sin(), max(), exp() and so forth: There is no "Math" object, these are just methods that embody mathematical algorithms. Not the best example, because in Ruby those methods are probably embedded right into the numeric classes as instance methods.
The case you mention is a bit confusing because Array's () method and Kernel's Array() method are in fact different methods that do similar things. Both are class methods.
Array() takes a list of arguments and makes and returns an array containing them.
Kernel.Array() takes a single argument of an "array-able" type, such as a sequence, and takes the values returned by this argument and builds an array from those.
UPDATE
The downvote was perhaps justified; I apologize for taking on a subject outside my area of expertise. I think I'll be deleting this answer soon.
# Chuck: I would sincerely hope that a language/library's official documentation would offer some meaningful clues as to how it works. This is what I consulted in answering this question.
The rdoc for Kernel.Array():
Returns arg as an Array. First tries to call arg.to_ary, then arg.to_a. If both fail, creates a single element array containing arg (unless arg is nil).
for Array.():
Returns a new array populated with the given objects.
I don't know about you, but I think if the docs vary that much then either they're talking about separate methods or the documentation is a train wreck.
# freeknight:
But everything in ruby is an object of some kind, even classes and modules. And Kernel.Array is actually a method call on an specific object - the Kernel object.
Yeah, under the covers it's similar in Java too. But the Array() method isn't doing anything with Kernel, any more than Array() is doing anything with the Array class object, so this is really only a semantic quibble. It's an instance method because you could hang it off class IPSocket if you were crazy enough, and it would still work the same way.
They are the same thing:
a = Kernel.Array('aa')
=> ["aa"]
a.class
=> Array
a = Array('aaa')
=> ["aaa"]
a.class
=> Array
Maybe there is an alias?

method_missing in "Programming Ruby" over my head

method_missing
*obj.method_missing( symbol h , args i ) → other_obj
Invoked by Ruby when obj is sent a
message it cannot handle. symbol is
the symbol for the method called, and
args are any arguments that were
passed to it. The example below
creates a class Roman, which responds
to methods with names consisting of
roman numerals, returning the
corresponding integer values. A more
typical use of method_missing is to
implement proxies, delegators, and
forwarders.
class Roman
def roman_to_int(str)
# ...
end
def method_missing(method_id)
str = method_id.id2name
roman_to_int(str)
end
end
r = Roman.new
r.iv ! 4
r.xxiii ! 23
r.mm ! 2000
I just heard about method-missing and went to find out more in Programming Ruby but the above explanation quoted from the book is over my head. Does anyone have an easier explanation? More specifically, is method-missing only used by the interpreter or is there ever a need to call it directly in a program (assuming I'm just writing web apps, as opposed to writing code for NASA)?
It's probably best to not think of ruby as having methods. When you call a ruby "method" you are actually sending a message to that instance (or class) and if you have defined a handler for the message, it is used to process and return a value.
So method_missing is a special definition that gets called whenever ruby cannot find an apropriate handler. You could also think of it like a * method.
Ruby doesn't have any type enforcement, and likewise doesn't do any checking as to what methods an object has when the script is first parsed, because this can be dynamically changed as the application runs.
What method_missing does, is let you intercept and handle calls to methods that don't exist for a given object. This provides the under-the-hood power behind pretty much every DSL (domain-specific language) written in Ruby.
In the case of the example, every one of 'r.iv', 'r.mm', and so on is actually a method call to the Roman object. Of course, it doesn't have an 'iv' or an 'mm' method, so instead control is passed to method_missing, which gets the name of the method that was called, as well as whatever arguments were passed.
method_missing then converts the method name from a symbol to a string, and parses it as a Roman number, returning the output as an integer.
It's basically a catch-all for messages that don't match up to any methods. It's used extensively in active record for dynamic finders. It's what lets you write something like this:
SomeModel.find_by_name_and_number(a_name, a_number)
The Model doesn't contain code for that find_by, so method_missing is called which looks at is says - I recognize that format, and carries it out. If it doesn't, then you get a method not found error.
In the Roman example you provide it illustrates how you can extend the functionality of a class without explicitly defining methods.
r.iv is not a method so method_missing catches it and calls roman_to_int on the method id "iv"
It's also useful when you want to handle unrecognized methods elsewhere, like proxies, delegators, and forwarders, as the documentation states.
You do not call "method_missing" (the interpreter calls it). Rather, you define it (override it) for a class which you want to make to be more flexible. As mentioned in other comments, the interpreter will call your version of method_missing when the class (or instance) does not ("explicitly"?) define the requested method. This gives you a chance to make something up, based on the ersatz method/message name.
Have you ever done any "reflection" programming in Java? Using this method would be as if the class to be accessed via reflection could look at the string (excuse me, "symbol") of the method name if a no-such-method exception was thrown, and then make something up as that method's implementation on the fly.
Dynamic programming is kind of a "one-up" on reflection.
Since you mention web apps I'll guess that you are familiar with Ruby on Rails. A good example of how method_missing can be used is the different find_by_<whatever> methods that's available. None of those methods actually exist! They are synthesized during run time. All of this magic happens because of how ruby intercepts invocations of non-existing methods.
You can read more about that and other uses of method_missing here.
ActiveRecord uses method_missing to define find_by methods. But since, method_missing is basically a last resort method, this can be a serious performance bottleneck. What I discovered is that ActiveRecord does some further awesome metaprogramming by defining the new finder method as a class method !! Thus, any further calls to the same finder method would not hit the method_missing because it is now a class method. For details about the actual code snippet from base.rb, click here.

Resources