Storing methods in arrays or hashes

Hey all,
I’m pretty new to ruby, and I absolutely love it. I have aquestion. I
have programmed in a language called lua before (which had real full-
fledged anonymous functions), and with a lua table, which is Lias
version of a hash and an arrary combined, you could do something like
this:

newtable = { 1 = function() print(“hi from 1”) end,
2 = function() print(“hi from 2”) end
}

even though some of you haven’t even ever heard of lua before, it’s
easy to guess what this does: it creates two keys, 1 and 2, in a
table, newtable, and assigns two functions as their values. After
doing that, you can do this:

newtable1

To call the function stored in newtable[1]. All that begs the
question: is something similar available in ruby?

On 12/24/2009 08:05 AM, Philliam A. wrote:

Hey all,
I’m pretty new to ruby, and I absolutely love it. I have aquestion. I
have programmed in a language called lua before (which had real full-
fledged anonymous functions), and with a lua table, which is Lias
version of a hash and an arrary combined, you could do something like

Just out of curiosity: where is the array in your Lua case? In Ruby you
would not need an Array for this - or rather, you need either an Array
or a Hash.

newtable1

To call the function stored in newtable[1]. All that begs the
question: is something similar available in ruby?

Yes. (I’m inclined to say “Of course!” :-)) Please see Bill’s
explanation.

Additional note: since the advent of Ruby 1.9 you can also use another
syntax for anonymous functions:

f = ->(args) { code }

newtable = {
1 => -> { puts “hi from 1” },
2 => -> { puts “hi from 2” },
}

If you only have numeric indexes in sequence you can also use an Array
instead of a Hash:

newtable = [
-> {}, # index 0
-> { puts “hi from 1” },
-> { puts “hi from 2” },
]

Kind regards

robert

On Dec 24, 4:59 am, Robert K. [email protected] wrote:

or a Hash.

doing that, you can do this:
syntax for anonymous functions:
instead of a Hash:


remember.guy do |as, often| as.you_can - without endhttp://blog.rubybestpractices.com/

Holy crap that’s awesome. Thanks for telling me about the new syntax
for anonymous function Rob, it just makes me love ruby even more now.
Thanks again guys.

On Thu, 2009-12-24 at 16:10 +0900, Philliam A. wrote:

This calls a dispatch.
Though I also don’t know how ruby will write it, but I think maybe using
symbols is a way.

Eva.

Philliam A. wrote:

newtable = { 1 = function() print(“hi from 1”) end,
2 = function() print(“hi from 2”) end
}

here’s an example, similar to the above, but

also passing an argument:

newhash = { 1 => lambda {|x| puts("#{x} from 1")},
2 => lambda {|x| puts("#{x} from 2")}
}

newhash[1].call(“hi”)
newhash[2][“bye”] # alternate call syntax

produces:

hi from 1
bye from 2

Hope this helps,

Bill