On 10/23/05, Bob Hutchison <hutch / recursive.ca> wrote:> Hi,>> The pickaxe book, on page 328 talks about naming of things in Ruby.> It says that reserved words should not be used as variable, method,> class, or module names.>> The key word here is 'should', because it seems that, for example> 'if' and 'def' both work as method names.>> I can certainly understand the convention of not using keywords, but> what is the actual constraint? (I generating code and I would like to> know what I MUST enforce as opposed to SHOULD enforce)
class Foo  def if; "if" end  def def; "def" end  def end; "end" endend    ==>nilFoo.new.if    ==>"if"Foo.new.def    ==>"def"Foo.new.end    ==>"end"$KCODE="u"    ==>"u"class Foo  def  3.14159 endend    ==>nilFoo.new.   ==>3.14159class Foo  define_method("!^@$&@**)(") do "!^@$&@**)(" endend    ==>#<Proc:0x0003a0c8@(irb):43>Foo.new.send "!^@$&@**)("    ==>"!^@$&@**)("class Foo  define_method("\0\0\0\0\0") do "null" endend    ==>#<Proc:0x000b0c90@(irb):47>Foo.new.send "\0\0\0\0\0"    ==>"null"Foo.new.send "\0"    ==>"null"
The only restrictions on a normal "def foo() ... end" type method isthat the ruby parser has to be able to parse the method name. Sopretty much any valid identifier will work.
When using define_method, everything from the first null forward getsstripped from the method name when it is created. So defining (orcalling, for that matter) a method named "\0\0\0\0\0" is like defining(or calling) a method named "". That's the  only *real* restriction Ican think of on method names. You can have unicode characters,keywords, operators, etc... though some of those are probably not agreat idea.
Basically, Ruby is pretty liberal in what it accepts. If it getsthrough the parser, it'll pretty much accept anything you throw at it.This makes it pretty powerful, but (of course) it also gives you thepower to shoot yourself in the foot. Or elsewhere :)
cheers,Mark
>> Cheers,> Bob>> ----> Bob Hutchison          -- blogs at <http://www.recursive.ca/hutch/>> Recursive Design Inc.  -- <http://www.recursive.ca/>> Raconteur              -- <http://www.raconteur.info/>>>>>>