Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > What this code means?

Reply
Thread Tools

What this code means?

 
 
MohsinHijazee
Guest
Posts: n/a
 
      01-25-2008
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
 
Reply With Quote
 
 
 
 
Stefan Lang
Guest
Posts: n/a
 
      01-25-2008
2008/1/25, MohsinHijazee <(E-Mail Removed)>:
> 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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
what is the difference between code inside a <script> tag and code in the code-behind file? keithb ASP .Net 1 03-29-2006 01:00 AM
Fire Code behind code AND Javascript code associated to a Button Click Event =?Utf-8?B?Q2FybG8gTWFyY2hlc29uaQ==?= ASP .Net 4 02-11-2004 07:31 AM
Re: Code Behind vs. no code behind: error Ben Miller [msft] ASP .Net 1 06-28-2003 01:46 AM
Re: C# Equivalent of VB.Net Code -- One line of code, simple Ian ASP .Net 0 06-25-2003 01:14 PM
Re: C# Equivalent of VB.Net Code -- One line of code, simple Ron ASP .Net 1 06-24-2003 07:18 PM



Advertisments