What this code means?

M

MohsinHijazee

Hello!
I am new to Ruby, can anyone explain what this code snippet is
trying to do?


module YourLastModule
class << self
def included(c)
class << c
def say_hellol(name)
return "Hello, " + name
end
end
end
end
end
 
S

Stefan Lang

2008/1/25 said:
Hello!
Hello!

I am new to Ruby, can anyone explain what this code snippet is
trying to do?

First you have to understand the following Ruby construct:

class << some_object
def hello
puts "hello"
end
end

The "class << some_object" line opens the "eigenclass"
of some_object. The eigenclass is Class object that
belongs solely to some_object and thus we're not
interfering with any other objects class. All methods
added in "class << some_object" belong only
to some_object.

some_object.hello # prints "hello"

Now to your example:

module YourLastModule

# At this point, self refers to YourLastModule

# Thus here we are opening the eigenclass
# of YourLastModule.
class << self

# This method is defined on the YourLastModule
# object (and _not_ on instances of YourLastModule).
#
# The included method of a module is called by
# Ruby when the module is included in a class
# or another module. The argument c is the including
# class or module.
def included(c)

# Here we open up the eigenclass of the including
# class.
class << c

# Adding a method to the including class object
# (the method is _not_ available to instances of the class).
def say_hello(name)
return "Hello, " + name
end

end
end
end
end

In effect, the example demonstrates how to add
class methods to including classes.

class Foo
include YourLastModule
end

Foo.say_hello("Arthur") # => "Hello, Arthur"

I'd say this stuff belongs into the advanced section
of ruby learning material.

HTH,
Stefan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top