On Aug 19, 2006, at 13:40, Jon wrote:

> Hi all,
>
> I'm a 'ruby nubie' and otherwise unfamiliar with the ':eval' technique
> it employs.
>
> Are there any decent reference guides to it's use?
>
> Alternatively, can anyone give me a quick explanation of what, when  
> and
> how to use it?
>
> This for example, from an ajax scaffold im working on, makes little
> sense to me (it doesn't help that it's also Saturday afternoonr!)
>
> :eval => "detail.bookings.collect{ |booking| booking.date }.join(',  
> ')"

There's actually several different things going on, so I'll give my  
best explanation one by one.

First, names prefixed with a colon, like :eval, are symbols.  If  
you're familiar with Lisp, then that's good, because they're quite  
similar to Lisp symbols.  If you're not familiar with symbols in  
Lisp, then a quick search of the mailing list archives should provide  
plenty of explanations for symbols.  For now, though, you can  
consider them as a literal value, a little like an integer (e.g., 12)  
but without all the arithmetic, basically, they have a unique value  
in and of themselves, and can be compared (:foo == :foo, :foo != :bar).

Next, you've got a hash literal - hash literals don't always need the  
enclosing {}.  The symbol is being used as a key in the hash, which  
is a very common use of symbols.  For example:

   p :foo => "bar", :moose => "squirrel"
   {:foo=>"bar", :moose=>"squirrel"}

So what you have is a hash whose key is the symbol :eval, and whose  
value is a string of Ruby code that looks a lot like something to do  
with ActiveRecord.  Perhaps the key to the puzzle is that there's an  
eval method in Ruby which takes a string and interprets it as Ruby  
code, for example:

   eval('p :foo => "bar", :moose => "squirrel"')

Will get the same result as the example above.

What I suspect is going on is that the hash is being used to (perhaps  
optionally) provide a snippet of Ruby code to be executed later in  
the program.

Symbols and hash literals creep up all over the place in Ruby code,  
so there's no particular advice I could give about when it's  
appropriate to use them.  Eval is somewhat trickier - it and its  
cousins instance_eval and class_eval which are used extensively in  
metaprogramming in Ruby, and it's obviously handy to be able to pass  
code snippets around as strings in some tasks.  They do have their  
pitfalls, though.  Again, a search of the mailing list should give  
interesting discussions about when where and how to use eval.

Hope that's of some help.

matthew smillie.