From: Philliam Auriemma Date: 2009-12-25T02:20:18+09:00 Subject: Re: Storing methods in arrays or hashes On Dec 24, 4:59 am, Robert Klemme wrote: > On 12/24/2009 08:05 AM, Philliam Auriemma 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. > > > 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: > > > newtable[1]() > > > 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 > > -- > 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.