What are the restrictions for method names in Ruby?
Method names in Ruby may contain upper-case and lower-case letters, numbers, underscores _
and the punctation signs !
, ?
, =
.
A method name can't begin with a number, and the characters !
, ?
and =
can only appear at the end.
Non-ASCII characters can be used in a method name, but this can lead to very confusing situations and should not be common practice.
It's good practice, while not mandatory, to start the method name with a lower-case character, because names that start with capital letters are constants in Ruby. It's still possible to use a constant name for a method, but you won't be able to invoke it without parentheses, because the interpeter will look-up for the name as a constant:
def Capital
nil
end
Capital # NameError: uninitialized constant Capital
Capital() # => nil
Some very widely and consistently used conventions when defining method names are:
Method names are full down-case, with underscores
_
as separators for words into the name (e.g.Math::sqrt
,Array#each_index
, ...).Predicates have a question mark
?
as last character (e.g.Array#empty?
,Hash#has_key?
, ...). While predicates usually return boolean values, this is not always the case: these methods just need to returnnil
orfalse
if the predicate evaluates to false, any other value otherwise (e.g.File::size?
returnsnil
if the file does not exist, the size of the file as anInteger
otherwise).Methods that modify the state of the object on which they are invoked, or that have an unusual behavior have an exclamation mark
!
as last character; this methods are sometimes called mutators because they usually are destructive or in-place versions of other methods (e.g.Array#sort!
,Array#slice!
, ...).Setters have an equal sign
=
as last character (e.g.Array#[]=
, ...); the Ruby interpeter offers syntactic sugar for invokation of setter methods:a = [4, 5, 6]
a[0] = 3 # Shorthand for a.[]=(0, 3)
Ruby also allows to define operators using the operator symbol as the method name:
╔═══════════════════════════╦═════════════════════════════════════════════╦═══════╗
║ Operators (by precedence) ║ Operations ║ Arity ║
╠═══════════════════════════╬═════════════════════════════════════════════╬═══════╣
║ ! ~ + ║ Boolean NOT, bitwise complement, unary plus ║ 1 ║
║ ║ (define with method name +@, Ruby 1.9+) ║ ║
║ ║ ║ ║
║ ** ║ Exponentiation ║ 2 ║
║ ║ ║ ║
║ - ║ Unary minus (define with method name -@) ║ 1 ║
║ ║ ║ ║
║ * / % ║ Multiplication, division, modulo ║ 2 ║
║ ║ ║ ║
║ + - ║ Addition, subtraction ║ 2 ║
║ ║ ║ ║
║ << >> ║ Bitwise shift ║ 2 ║
║ ║ ║ ║
║ & ║ Bitwise AND ║ 2 ║
║ ║ ║ ║
║ | ^ ║ Bitwise OR, Bitwise XOR ║ 2 ║
║ ║ ║ ║
║ < <= => > ║ Ordering ║ 2 ║
║ ║ ║ ║
║ == === != =~ !~ <=> ║ Equality, pattern matching, comparison ║ 2 ║
╚═══════════════════════════╩═════════════════════════════════════════════╩═══════╝
Unary operator methods are passed no arguments; binary operator methods are passed an argument, and operate on it and on self
.
It's important to adhere strictly to the arity of the operators; while it is possible to define operator methods with a different arity (e.g. a +
method that takes two arguments), Ruby would not allow you to call the method with operator syntax (it would however work with dot syntax).
It's good practice to adhere to the original semantics of the operators as much as possible: it should be intuitive to someone who knows the original meaning of the operator how it works with user defined classes.
The language also offers syntactic sugar for the special, non-operator ,[]
method that is normally used for accessing array and hash values. The []
method can be defined with arbitrary arity.
For every binary operator in the table, except ordering, equality, comparison and pattern matching, Ruby also offers shorthand for abbreviated assignment (e.g. x += y
expands to x = x + y
); you can't define them as methods, but you can alter their behavior defining the operators on which they're based.
None of these characters can be used inside normal method names (e.g. do&print
or start-up
are not valid method names).
What's the maximum length of a method name in ruby?
RubyMine lies :-) Or at least does not mean that it is a limitation of Ruby interpreter.
looong_name = "a" * 10000; # => "What Are the Restrictions For Method Names in Rubya.....
a_class = Class.new
a_class.__send__(:define_method, looong_name) { :hello }
a_class.new.__send__(looong_name) # => :hello
puts a_class.instance_methods.inspect # you better not run this :-)
Method Syntax with restrictions not running
Consider something like this:
def greeter(name)
"Hi there #{name}!"
end
def by_three?(number)
number % 3 == 0
end
You can check these in irb
:
1.9.3p327 :010 > greeter 'joe'
=> "Hi there joe!"
1.9.3p327 :011 > by_three? 9
=> true
1.9.3p327 :012 > by_three? 10
=> false
Notes:
In ruby
, it's common practice to not use return
unless it's absolutely necessary, since the result of the last expression executed in the method is automatically returned as the value of the method.
Also, my interpretation of the question you're working on looks like it wants your methods to take parameters, so I've removed the gets
calls to read from standard input, and instead expect the methods to operate on the parameter passed to it. (Though I could certainly be wrong in my reading of the codeacademy question.)
Variables in ruby method names
You can use #send method to call object's method by method's name:
object.send(:foo) # same as object.foo
You can pass arguments with to invoked method:
object.send(:foo, 1, "bar", 1.23) # same as object.foo(1, "bar", 1.23)
So, if you have attribute name in variable "attribute" you can read object's attribute with
object.send(attribute.to_sym)
and write attribute's value with
object.send("#{attribute}=".to_sym, value)
In Ruby 1.8.6 #send method can execute any object's method regardless of its visibility (you can e.g. call private methods). This is subject to change in future versions of Ruby and you shouldn't rely on it. To execute private methods, use #instance_eval:
object.instance_eval {
# code as block, can reference variables in current scope
}
# or
object.instance_eval <<-CODE
# code as string, can generate any code text
CODE
Update
You can use public_send
to call methods with regard to visibility rules.
object.public_send :public_foo # ok
object.public_send :private_bar # exception
What is a Ruby regex to match a function name?
You can take advantage of the fact that Symbol#inspect
quotes the name when it is not a valid identifier. A valid symbol becomes ":hello!"
when inspected, but an invalid one becomes ":\"invalid!?\""
. This handles exotic symbols like :foo=
, :[]=
, and any other valid method name.
Adding the additional requirement that @
-names are valid identifiers but not valid method names gives us this:
class Symbol
def method_name?
return /[@$"]/ !~ inspect
end
end
What are the uppercase and lowercase rules of ruby method name?
By convention, things that start with uppercase letters are constants. When you invoke SayHi
, you're telling Ruby to look for a constant with this name. Of course, there isn't one, so it fails.
If you want to invoke the method, you'll need to add a pair of parentheses. For example,
def S
puts "shazam!"
end
S #=> NameError: uninitialized constant S
S() #=> "shazam!"
Inside of a class, the resolution rules are a little different. Let's define a simple class with a constant and a method named to look like a constant:
irb(main):001:0> class C
irb(main):002:1> A = "x"
irb(main):003:1> def B
irb(main):004:2> puts "B() invoked"
irb(main):005:2> end
irb(main):006:1> end
=> nil
Now, A
is certainly a constant. But what about B
?
irb(main):008:0> C.const_defined?("A")
=> true # A is a constant!
irb(main):009:0> C.const_defined?("B")
=> false # B looks like a constant but isn't, because we
# used "def" to create it. "def" is for methods,
# not constants.
So it isn't a constant, just a method with that name. When we try to access B
from an instance of C
, now Ruby's looking for a method:
irb(main):011:0> C.new.B
B() invoked
=> nil
If we wanted to access a constant of C
instead, we use the scope qualifier ::
:
irb(main):012:0> C::A
=> "x"
What is the other object and how does it work?
In ruby, operators are in fact method calls. If you have two variables a
and b
and want to check their equality, you generally write a == b
, but you could write a.==(b)
. The last syntax shows what happens during an equality check : ruby calls a
's method ==
and passes it b
as an argument.
You can implement custom equality check in your classes by defining the ==
and/or the eql?
methods. In your example, other
is simply the name of the argument it receives.
class Person
attr_accessor :name
def initialize name
@name = name
end
end
a = Person.new("John")
b = Person.new("John")
a == b # --> false
class Person
def == other
name == other.name
end
end
a == b # --> true
For your second question, the only methods starting with ==
you're allowed to implement are ==
and ===
. Check here for the full list of restrictions on method names in ruby: What are the restrictions for method names in Ruby?
Related Topics
How to Pass Command Line Arguments to a Rake Task
Does Ruby Have Real Multithreading
Difference Between Rake Db:Migrate Db:Reset and Db:Schema:Load
What Is the Ruby ≪=≫ (Spaceship) Operator
Why Use Ruby'S Attr_Accessor, Attr_Reader and Attr_Writer
How to Redirect to a 404 in Rails
Why Does Ruby 1.9.2 Remove "." from Load_Path, and What's the Alternative
How to Find Where a Method Is Defined At Runtime
Ruby Block and Unparenthesized Arguments
How to Call Methods Dynamically Based on Their Name
Difference Between "Or" and || in Ruby