Use parameter to determine which method is called inside function

Hi Everyone,
I am very new to Ruby but have overcome quite a few problems on the road
already. However, this one seems to be a tough nut to crack for me, so
any help from you would be highly appreciated. OK. So here is what I am
trying to achieve:

EXAMPLE:

array_of_objects = [obj1,obj2,obj3]

def my_method(arg1,arg2)

arg1.each { |object|

puts object.arg2 #want to substitute arg2

}

end

my_method(array_of_objects,‘desired property’)

END EXAMPLE

#want to substitue arg2 with the property/method call given as input
when calling the method
#The object property can be for instance the length or width or any
method you can call on the object in the array_of_objects,
#but how can I substitute this function, or method call into the method
call for the object?
#I am guessing a proc or a lambda or block is what I an looking for, but
I cannot seem to get it to work…
#would be very good as one function then can return any properties,
instead of having to make one function for each property.

#Would be very grateful if anyone could help me with this as I am very
new to ruby :slight_smile:

This is ‘dynamic method call’

a1 = [1,2,3]
a2 = [“a”,4,5,“b”]

a1.send(:length) # the same as ‘a1.length’
3

So your method would look like this:

def my_method(arg1, arg2)
arg1.send(arg2)
end

where ‘arg2’ must be a Symbol (ie. :size)

Proc and Lambda are different beasts, you need them when you want to
pass an anonymous method as an object to a named method (so the named
method would probably run that anonymous method).
In syntax, a Proc or Lambda is very similar to those code blocks you are
passing to certain method, like:

[1,2,4,8,16,32].each { |x| puts x*x }

There are a few differences among code block, proc and lambda, this is a
lengthy topic in Ruby.

AWESOME!
Thanks a lot Földes, that was exactly what I was looking for!
Can be frustrating sometimes when you know exactly what you want, but
not how to do it…hehe

Have a great evening!
Eirik

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs