Reputation: 168199
What strings can be a method name for Ruby? I particularly want to know in what way a non word character can be part of a method name. Please give an exhaustive set of rules/lists.
Edit
Phrogz' answers to the question that Josh Lee links has a link to the following page, but that is from several years ago, and is outdated. For example, Proc#()
is missing. Does anyone know of an updated one?
Upvotes: 2
Views: 532
Reputation: 369526
Any sequence of Unicode characters is a valid method name. For example:
class Test
define_method :' ??? _ µµµµ . . . ' do puts 'Hello' end
end
Test.instance_methods
# => [:' ??? _ µµµµ . . . ']
Test.new.send :' ??? _ µµµµ . . . '
# Hello
Upvotes: 3
Reputation: 160571
You can use ASCII, UTF-8 and Unicode characters as the names of methods. I imagine that whitespace (\s
) characters wouldn't work simply because the parser would complain. Just set up the magic line so Ruby knows what to expect.
http://www.oreillynet.com/ruby/blog/2007/10/fun_with_unicode_1.html and http://rosettacode.org/wiki/Unicode_variable_names#Ruby and http://www.sw.it.aoyama.ac.jp/2009/pub/IUC33-ruby1.9/. Phrogz has a nice regex in https://stackoverflow.com/a/4379197/128421 which covers the ASCII characters.
Also, here on Stack Overflow, this has been discussed nicely in "How does Ruby 1.9 handle character cases in source code?". Because of the age of that question I'm not marking this as a duplicate, but it does deserve to be referenced.
The question that should be asked though, is, should non-ASCII characters be used in method names? Yes, they're cute, and they might be symbolic, but they can be a pain to type, especially for those who don't have the ability to type in the characters for one reason or another. Creating a method name or constant containing π or λ might be hard to type if they're in a gem.
Also note that $KCODE
, mentioned on several of the linked paged, is now deprecated in Ruby 1.9.1+ so you'll need to use magic lines.
Upvotes: 1
Reputation: 46677
According to pickaxe (Programming Ruby, The Pragmatic Programmers):
Local variables, method parameters, and method names should all start with a lowercase letter or an underscore... Following this initial character, a name can be any combination of letters, digits, and underscores (with the proviso that the character following an @ sign may not be a digit)... Method names may end with the characters ?, !, and =.
Upvotes: 3