From: Bob Hutchison Date: 2005-10-24T03:20:16+09:00 Subject: Re: What are method/attribute names that are actually illegal On Oct 23, 2005, at 1:54 PM, Mark Hubbart wrote: > On 10/23/05, Bob Hutchison 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" end > end > ==>nil > Foo.new.if > ==>"if" > Foo.new.def > ==>"def" > Foo.new.end > ==>"end" > $KCODE="u" > ==>"u" > class Foo > def �; 3.14159 end > end > ==>nil > Foo.new.� > ==>3.14159 > class Foo > define_method("!^@$&@**)(") do "!^@$&@**)(" end > end > ==># > Foo.new.send "!^@$&@**)(" > ==>"!^@$&@**)(" > class Foo > define_method("\0\0\0\0\0") do "null" end > end > ==># > 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 is > that the ruby parser has to be able to parse the method name. So > pretty much any valid identifier will work. > > When using define_method, everything from the first null forward gets > stripped from the method name when it is created. So defining (or > calling, 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 I > can think of on method names. You can have unicode characters, > keywords, operators, etc... though some of those are probably not a > great idea. > > Basically, Ruby is pretty liberal in what it accepts. If it gets > through the parser, it'll pretty much accept anything you throw at it. > This makes it pretty powerful, but (of course) it also gives you the > power to shoot yourself in the foot. Or elsewhere :) Thanks Mark. This is very good news for my users (for now, that would be me :-) I think very dangerous names can be dealt with, if only by aliasing the names to something reasonable. I have no control over the original names at all, so... How does Ruby define the first character of a constant? just curious since I see that � cannot be the first character of a class name. Cheers, Bob > > cheers, > Mark > > >> >> Cheers, >> Bob >> >> ---- >> Bob Hutchison -- blogs at >> Recursive Design Inc. -- >> Raconteur -- >> >> >> >> >> > ---- Bob Hutchison -- blogs at Recursive Design Inc. -- Raconteur --