U:RDoc::TopLevel[ i I"syntax/methods.rdoc:EFcRDoc::Parser::Simpleo:RDoc::Markup::Document:@parts[S:RDoc::Markup::Heading:
leveli: textI"Methods;To:RDoc::Markup::BlankLine o:RDoc::Markup::Paragraph;[I"SMethods implement the functionality of your program. Here is a simple method ;TI"definition:;T@
o:RDoc::Markup::Verbatim;[I"def one_plus_one
;TI"
1 + 1
;TI" end
;T:@format0o;
;[I"SA method definition consists of the +def+ keyword, a method name, the body of ;TI"Tthe method, +return+ value and the +end+ keyword. When called the method will ;TI">execute the body of the method. This method returns +2+.;T@
o;
;[I"TThis section only covers defining methods. See also the {syntax documentation ;TI"?on calling methods}[rdoc-ref:syntax/calling_methods.rdoc].;T@
S; ;
i;I"Method Names;T@
o;
;[ I"TMethod names may be one of the operators or must start a letter or a character ;TI"Pwith the eight bit set. It may contain letters, numbers, an _
;TI"T(underscore or low line) or a character with the eight bit set. The convention ;TI"His to use underscores to separate words in a multiword method name:;T@
o;;[I"def method_name
;TI"0 puts "use underscores to separate words"
;TI" end
;T;0o;
;[
I"RRuby programs must be written in a US-ASCII-compatible character set such as ;TI"NUTF-8, ISO-8859-1 etc. In such character sets if the eight bit is set it ;TI"Uindicates an extended character. Ruby allows method names and other identifiers ;TI"Sto contain such characters. Ruby programs cannot contain some characters like ;TI"#ASCII NUL (\x00
).;T@
o;
;[I":The following are the examples of valid ruby methods:;T@
o;;[I"def hello
;TI" "hello"
;TI" end
;TI"
;TI"def こんにちは
;TI"& puts "means hello in Japanese"
;TI" end
;T;0o;
;[I"PTypically method names are US-ASCII compatible since the keys to type them ;TI"exist on all keyboards.;T@
o;
;[I"NMethod names may end with a !
(bang or exclamation mark), a ;TI"B?
(question mark) or =
equals sign.;T@
o;
;[I"PThe bang methods (!
at the end of method name) are called and ;TI"Sexecuted just like any other method. However, by convention, a method with an ;TI"Qexclamation point or bang is considered dangerous. In ruby core library the ;TI"Tdangerous method implies that when a method ends with a bang (!
), ;TI"Pit indicates that unlike its non-bang equivalent, permanently modifies its ;TI"Ereceiver. Almost always, ruby core library will have a non-bang ;TI"Tcounterpart (method name which does NOT end with !
) of every bang ;TI"Rmethod (method name which does end with !
) that does not modify ;TI"Othe receiver. This convention is typically true for ruby core library but ;TI"7may or may not hold true for other ruby libraries.;T@
o;
;[I"RMethods that end with a question mark by convention return boolean, but they ;TI"Omay not always return just +true+ or +false+. Often, they will return an ;TI"9object to indicate a true value (or "truthy" value).;T@
o;
;[I"NMethods that end with an equals sign indicate an assignment method. For ;TI"Tassignment methods, the return value is ignored and the arguments are returned ;TI"
instead.;T@
o;
;[I"KThese are method names for the various ruby operators. Each of these ;TI"Poperators accept only one argument. Following the operator is the typical ;TI"Ruse or name of the operator. Creating an alternate meaning for the operator ;TI"Lmay lead to confusion as the user expects plus to add things, minus to ;TI"Qsubtract things, etc. Additionally, you cannot alter the precedence of the ;TI"operators.;T@
o:RDoc::Markup::List:
@type: NOTE:@items[o:RDoc::Markup::ListItem:@label[I"+
;T;[o;
;[I"add;To;;[I"-
;T;[o;
;[I"
subtract;To;;[I"*
;T;[o;
;[I"
multiply;To;;[I"**
;T;[o;
;[I"
power;To;;[I"/
;T;[o;
;[I"divide;To;;[I"%
;T;[o;
;[I"modulus division, String#%;To;;[I"&
;T;[o;
;[I"AND;To;;[I"^
;T;[o;
;[I"XOR (exclusive OR);To;;[I">>
;T;[o;
;[I"right-shift;To;;[I"<<
;T;[o;
;[I"left-shift, append;To;;[I"==
;T;[o;
;[I"
equal;To;;[I"!=
;T;[o;
;[I"not equal;To;;[I"===
;T;[o;
;[I"#case equality. See Object#===;To;;[I"=~
;T;[o;
;[I"7pattern match. (Not just for regular expressions);To;;[I"!~
;T;[o;
;[I"does not match;To;;[I"<=>
;T;[o;
;[I"7comparison aka spaceship operator. See Comparable;To;;[I"<
;T;[o;
;[I"less-than;To;;[I"<=
;T;[o;
;[I"less-than or equal;To;;[I">
;T;[o;
;[I"greater-than;To;;[I">=
;T;[o;
;[I"greater-than or equal;T@
o;
;[I"TTo define unary methods minus, plus, tilde and not (!
) follow the ;TI"Noperator with an @
as in +@
or !@
:;T@
o;;[I"
class C
;TI" def -@
;TI") puts "you inverted this object"
;TI" end
;TI" end
;TI"
;TI"obj = C.new
;TI"
;TI".-obj # prints "you inverted this object"
;T;0o;
;[I")Unary methods accept zero arguments.;T@
o;
;[I"PAdditionally, methods for element reference and assignment may be defined: ;TI"R[]
and []=
respectively. Both can take one or more ;TI"4arguments, and element reference can take none.;T@
o;;[I"
class C
;TI" def [](a, b)
;TI" puts a + b
;TI" end
;TI"
;TI" def []=(a, b, c)
;TI" puts a * b + c
;TI" end
;TI" end
;TI"
;TI"obj = C.new
;TI"
;TI" obj[2, 3] # prints "5"
;TI"!obj[2, 3] = 4 # prints "10"
;T;0S; ;
i;I"Return Values;T@
o;
;[ I"UBy default, a method returns the last expression that was evaluated in the body ;TI"Tof the method. In the example above, the last (and only) expression evaluated ;TI"Qwas the simple sum 1 + 1
. The +return+ keyword can be used to ;TI"4make it explicit that a method returns a value.;T@
o;;[I"def one_plus_one
;TI" return 1 + 1
;TI" end
;T;0o;
;[I"OIt can also be used to make a method return before the last expression is ;TI"evaluated.;T@
o;;[ I"def two_plus_two
;TI" return 2 + 2
;TI"3 1 + 1 # this expression is never evaluated
;TI" end
;T;0o;
;[I"ONote that for assignment methods the return value will always be ignored. ;TI",Instead, the argument will be returned:;T@
o;;[
I"def a=(value)
;TI" return 1 + value
;TI" end
;TI"
;TI"p(a = 5) # prints 5
;T;0S; ;
i;I"
Scope;T@
o;
;[I",The standard syntax to define a method:;T@
o;;[I"def my_method
;TI"
# ...
;TI" end
;T;0o;
;[I"Radds the method to a class. You can define an instance method on a specific ;TI"$class with the +class+ keyword:;T@
o;;[
I"
class C
;TI" def my_method
;TI" # ...
;TI" end
;TI" end
;T;0o;
;[I"TA method may be defined on another object. You may define a "class method" (a ;TI"Rmethod that is defined on the class, not an instance of the class) like this:;T@
o;;[
I"
class C
;TI" def self.my_method
;TI" # ...
;TI" end
;TI" end
;T;0o;
;[I"THowever, this is simply a special case of a greater syntactical power in Ruby, ;TI"Othe ability to add methods to any object. Classes are objects, so adding ;TI"@class methods is simply adding methods to the Class object.;T@
o;
;[I"?The syntax for adding a method to an object is as follows:;T@
o;;[I"greeting = "Hello"
;TI"
;TI"def greeting.broaden
;TI" self + ", world!"
;TI" end
;TI"
;TI"0greeting.broaden # returns "Hello, world!"
;T;0o;
;[ I"M+self+ is a keyword referring to the current object under consideration ;TI"Mby the compiler, which might make the use of +self+ in defining a class ;TI"Mmethod above a little clearer. Indeed, the example of adding a +hello+ ;TI"8method to the class +String+ can be rewritten thus:;T@
o;;[I"def String.hello
;TI" "Hello, world!"
;TI" end
;T;0o;
;[I"UA method defined like this is called a "singleton method". +broaden+ will only ;TI"Uexist on the string instance +greeting+. Other strings will not have +broaden+.;T@
S; ;
i;I"Overriding;T@
o;
;[
I"TWhen Ruby encounters the +def+ keyword, it doesn't consider it an error if the ;TI"Dmethod already exists: it simply redefines it. This is called ;TI"N_overriding_. Rather like extending core classes, this is a potentially ;TI"Udangerous ability, and should be used sparingly because it can cause unexpected ;TI"6results. For example, consider this irb session:;T@
o;;[I">> "43".to_i
;TI"=> 43
;TI">> class String
;TI">> def to_i
;TI">> 42
;TI">> end
;TI">> end
;TI"=> nil
;TI">> "43".to_i
;TI"=> 42
;T;0o;
;[I"KThis will effectively sabotage any code which makes use of the method ;TI"<String#to_i
to parse numbers from strings.;T@
S; ;
i;I"Arguments;T@
o;
;[I"OA method may accept arguments. The argument list follows the method name:;T@
o;;[I"def add_one(value)
;TI" value + 1
;TI" end
;T;0o;
;[ I"RWhen called, the user of the +add_one+ method must provide an argument. The ;TI"Targument is a local variable in the method body. The method will then add one ;TI"Kto this argument and return the value. If given +1+ this method will ;TI"return +2+.;T@
o;
;[I"7The parentheses around the arguments are optional:;T@
o;;[I"def add_one value
;TI" value + 1
;TI" end
;T;0o;
;[I"1Multiple arguments are separated by a comma:;T@
o;;[I"def add_values(a, b)
;TI"
a + b
;TI" end
;T;0o;
;[I"OWhen called, the arguments must be provided in the exact order. In other ;TI")words, the arguments are positional.;T@
S; ;
i;I"Default Values;T@
o;
;[I"'Arguments may have default values:;T@
o;;[I"def add_values(a, b = 1)
;TI"
a + b
;TI" end
;T;0o;
;[I"RThe default value does not need to appear first, but arguments with defaults ;TI"+must be grouped together. This is ok:;T@
o;;[I"%def add_values(a = 1, b = 2, c)
;TI" a + b + c
;TI" end
;T;0o;
;[I"#This will raise a SyntaxError:;T@
o;;[I"%def add_values(a = 1, b, c = 1)
;TI" a + b + c
;TI" end
;T;0S; ;
i;I"Array Decomposition;T@
o;
;[I"LYou can decompose (unpack or extract values from) an Array using extra ;TI""parentheses in the arguments:;T@
o;;[
I"def my_method((a, b))
;TI" p a: a, b: b
;TI" end
;TI"
;TI"my_method([1, 2])
;T;0o;
;[I"This prints:;T@
o;;[I"{:a=>1, :b=>2}
;T;0o;
;[I"JIf the argument has extra elements in the Array they will be ignored:;T@
o;;[
I"def my_method((a, b))
;TI" p a: a, b: b
;TI" end
;TI"
;TI"my_method([1, 2, 3])
;T;0o;
;[I"'This has the same output as above.;T@
o;
;[I"SYou can use a *
to collect the remaining arguments. This splits ;TI"0an Array into a first element and the rest:;T@
o;;[
I"def my_method((a, *b))
;TI" p a: a, b: b
;TI" end
;TI"
;TI"my_method([1, 2, 3])
;T;0o;
;[I"This prints:;T@
o;;[I"{:a=>1, :b=>[2, 3]}
;T;0o;
;[I"QThe argument will be decomposed if it responds to #to_ary. You should only ;TI"Ddefine #to_ary if you can use your object in place of an Array.;T@
o;
;[I"OUse of the inner parentheses only uses one of the sent arguments. If the ;TI"Oargument is not an Array it will be assigned to the first argument in the ;TI"Rdecomposition and the remaining arguments in the decomposition will be +nil+:;T@
o;;[
I"!def my_method(a, (b, c), d)
;TI" p a: a, b: b, c: c, d: d
;TI" end
;TI"
;TI"my_method(1, 2, 3)
;T;0o;
;[I"This prints:;T@
o;;[I"${:a=>1, :b=>2, :c=>nil, :d=>3}
;T;0o;
;[I",You can nest decomposition arbitrarily:;T@
o;;[I" def my_method(((a, b), c))
;TI"
# ...
;TI" end
;T;0S; ;
i;I"Array/Hash Argument;T@
o;
;[I"TPrefixing an argument with *
causes any remaining arguments to be ;TI"converted to an Array:;T@
o;;[
I"&def gather_arguments(*arguments)
;TI" p arguments
;TI" end
;TI"
;TI"1gather_arguments 1, 2, 3 # prints [1, 2, 3]
;T;0o;
;[I"TThe array argument must be the last positional argument, it must appear before ;TI"any keyword arguments.;T@
o;
;[I"TThe array argument will capture a Hash as the last entry if a hash was sent by ;TI"/the caller after all positional arguments.;T@
o;;[I"4gather_arguments 1, a: 2 # prints [1, {:a=>2}]
;T;0o;
;[I"THowever, this only occurs if the method does not declare any keyword arguments.;T@
o;;[I"=def gather_arguments_keyword(*positional, keyword: nil)
;TI"1 p positional: positional, keyword: keyword
;TI" end
;TI"
;TI"-gather_arguments_keyword 1, 2, three: 3
;TI"8#=> raises: unknown keyword: three (ArgumentError)
;T;0o;
;[I"KAlso, note that a bare *
can be used to ignore arguments:;T@
o;;[I"def ignore_arguments(*)
;TI" end
;T;0S; ;
i;I"Keyword Arguments;T@
o;
;[I"OKeyword arguments are similar to positional arguments with default values:;T@
o;;[I")def add_values(first: 1, second: 2)
;TI" first + second
;TI" end
;T;0o;
;[I"GArbitrary keyword arguments will be accepted with **
:;T@
o;;[I".def gather_arguments(first: nil, **rest)
;TI" p first, rest
;TI" end
;TI"
;TI"4gather_arguments first: 1, second: 2, third: 3
;TI"-# prints 1 then {:second=>2, :third=>3}
;T;0o;
;[I"RWhen calling a method with keyword arguments the arguments may appear in any ;TI"Sorder. If an unknown keyword argument is sent by the caller an ArgumentError ;TI"is raised.;T@
o;
;[I"LWhen mixing keyword arguments and positional arguments, all positional ;TI"8arguments must appear before any keyword arguments.;T@
S; ;
i;I"Block Argument;T@
o;
;[I"JThe block argument is indicated by &
and must come last:;T@
o;;[I"def my_method(&my_block)
;TI" my_block.call(self)
;TI" end
;T;0o;
;[I"RMost frequently the block argument is used to pass a block to another method:;T@
o;;[I"def each_item(&block)
;TI" @items.each(&block)
;TI" end
;T;0o;
;[ I"RIf you are only going to call the block and will not otherwise manipulate it ;TI"Oor send it to another method using yield
without an explicit ;TI"Rblock parameter is preferred. This method is equivalent to the first method ;TI"in this section:;T@
o;;[I"def my_method
;TI" yield self
;TI" end
;T;0o;
;[ I"OThere is also a performance benefit to using yield over a calling a block ;TI"Rparameter. When a block argument is assigned to a variable a Proc object is ;TI"Ncreated which holds the block. When using yield this Proc object is not ;TI"
created.;T@
o;
;[I"RIf you only need to use the block sometimes you can use Proc.new to create a ;TI"Sproc from the block that was passed to your method. See Proc.new for further ;TI"
details.;T@
S; ;
i;I"Exception Handling;T@
o;
;[I"PMethods have an implied exception handling block so you do not need to use ;TI"2+begin+ or +end+ to handle exceptions. This:;T@
o;;[I"def my_method
;TI"
begin
;TI", # code that may raise an exception
;TI" rescue
;TI" # handle exception
;TI" end
;TI" end
;T;0o;
;[I"May be written as:;T@
o;;[
I"def my_method
;TI"* # code that may raise an exception
;TI"rescue
;TI" # handle exception
;TI" end
;T;0o;
;[I"VIf you wish to rescue an exception for only part of your method, use +begin+ and ;TI"9+end+. For more details see the page on {exception ;TI"0handling}[rdoc-ref:syntax/exceptions.rdoc].;T:
@file@:0@omit_headings_from_table_of_contents_below0