how can we call a method without using . operator

R

ruby rails

Hi all,
This might sound a bit wierd but I would like to know if
there are any other ways of calling a method without using . operator or
calling send().

Is it possible using blocks or something else?
 
B

Brian Candler

ruby said:
This might sound a bit wierd but I would like to know if
there are any other ways of calling a method without using . operator or
calling send().

(or __send__ presumably). How about this one?

def foo
puts "hello"
end

m = method:)foo)
m[]

What are you trying to achieve anyway?
 
J

James Coglan

[Note: parts of this message were removed to make it a legal post.]

2009/1/19 ruby rails said:
Hi all,
This might sound a bit wierd but I would like to know if
there are any other ways of calling a method without using . operator or
calling send().



You could write a DSL that would make it look like you weren't doing dot or
send() but at some level you're going have to use one of those, or maybe
instance_eval. e.g.:

objects = {
:foo => foo_object
}

def method_missing(name, method)
objects[name.to_sym].__send__(method)
end

# calls foo_object.bar_method
foo_object :bar_method

It might be helpful if we knew the problem you're trying to solve -- can you
give us any more info?
 
J

James Coglan

[Note: parts of this message were removed to make it a legal post.]
objects = {
:foo => foo_object
}

def method_missing(name, method)
objects[name.to_sym].__send__(method)
end

# calls foo_object.bar_method
foo_object :bar_method


Correction: final line should have been
foo :bar_method
 
R

ruby rails

James said:
2009/1/19 ruby rails <[email protected]>


It might be helpful if we knew the problem you're trying to solve -- can
you
give us any more info?
I was asked this question by one of y interviewer...May be he is testing
my meta-programming skills...
 
R

Robert Klemme

I was asked this question by one of y interviewer...May be he is testing
my meta-programming skills...

No meta programming needed

irb(main):001:0> "foo".instance_eval { puts length }
3
=> nil

Cheers

robert
 
T

The Higgs bozo

ruby said:
Hi all,
This might sound a bit wierd but I would like to know if
there are any other ways of calling a method without using . operator or
calling send().

Is it possible using blocks or something else?

Look Ma, no dots!

class Foo
def hello
puts "hello!"
end
end

eval "Foo\056new\056hello"
#=> hello!

I will send my contact info via email so that I may receive my prize.
 
S

Simon Chiang

One more way uses colons:

a = [1,2]
a::length # => 2
a::push(3) # => [1,2,3]
a::length # => 3
 

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

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top