⚝
One Hat Cyber Team
⚝
Your IP:
216.73.216.13
Server IP:
109.199.105.153
Server:
Linux connect.inboxifs.com 5.15.0-152-generic #162-Ubuntu SMP Wed Jul 23 09:48:42 UTC 2025 x86_64
Server Software:
Apache
PHP Version:
8.2.29
Buat File
|
Buat Folder
Eksekusi
Dir :
~
/
usr
/
share
/
ri
/
3.0.0
/
system
/
syntax
/
View File Name :
page-methods_rdoc.ri
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"Qwith the eighth bit set. It may contain letters, numbers, an <code>_</code> ;TI"U(underscore or low line) or a character with the eighth 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"OUTF-8, ISO-8859-1 etc. In such character sets if the eighth 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 (<code>\x00</code>).;T@ o; ;[I"6The following are 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 <code>!</code> (bang or exclamation mark), a ;TI"E<code>?</code> (question mark), or <code>=</code> (equals sign).;T@ o; ;[I"TThe bang methods (<code>!</code> at the end of the method name) are called and ;TI"Sexecuted just like any other method. However, by convention, a method with an ;TI"Sexclamation point or bang is considered dangerous. In Ruby's core library the ;TI"Tdangerous method implies that when a method ends with a bang (<code>!</code>), ;TI"Pit indicates that unlike its non-bang equivalent, permanently modifies its ;TI"Ireceiver. Almost always, the Ruby core library will have a non-bang ;TI"Tcounterpart (method name which does NOT end with <code>!</code>) of every bang ;TI"Rmethod (method name which does end with <code>!</code>) that does not modify ;TI"Sthe receiver. This convention is typically true for the 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"HMethods that end with an equals sign indicate an assignment method.;T@ o; ;[I"KThese are method names for the various Ruby operators. Each of these ;TI"Qoperators accepts 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"<code>+</code> ;T;[o; ;[I"add;To;;[I"<code>-</code> ;T;[o; ;[I" subtract;To;;[I"<code>*</code> ;T;[o; ;[I" multiply;To;;[I"<code>**</code> ;T;[o; ;[I" power;To;;[I"<code>/</code> ;T;[o; ;[I"divide;To;;[I"<code>%</code> ;T;[o; ;[I"modulus division, String#%;To;;[I"<code>&</code> ;T;[o; ;[I"AND;To;;[I"<code>^</code> ;T;[o; ;[I"XOR (exclusive OR);To;;[I"<code>>></code> ;T;[o; ;[I"right-shift;To;;[I"<code><<</code> ;T;[o; ;[I"left-shift, append;To;;[I"<code>==</code> ;T;[o; ;[I" equal;To;;[I"<code>!=</code> ;T;[o; ;[I"not equal;To;;[I"<code>===</code> ;T;[o; ;[I"#case equality. See Object#===;To;;[I"<code>=~</code> ;T;[o; ;[I"7pattern match. (Not just for regular expressions);To;;[I"<code>!~</code> ;T;[o; ;[I"does not match;To;;[I"<code><=></code> ;T;[o; ;[I"7comparison aka spaceship operator. See Comparable;To;;[I"<code><</code> ;T;[o; ;[I"less-than;To;;[I"<code><=</code> ;T;[o; ;[I"less-than or equal;To;;[I"<code>></code> ;T;[o; ;[I"greater-than;To;;[I"<code>>=</code> ;T;[o; ;[I"greater-than or equal;T@ o; ;[I"ITo define unary methods minus and plus, follow the operator with an ;TI"*<code>@</code> as in <code>+@</code>:;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"HThe <code>@</code> is needed to differentiate unary minus and plus ;TI"4operators from binary minus and plus operators.;T@ o; ;[I"KYou can also follow tilde and not (<code>!</code>) unary methods with ;TI"I<code>@</code>, but it is not required as there are no binary tilde ;TI"and not operators.;T@ o; ;[I")Unary methods accept zero arguments.;T@ o; ;[I"PAdditionally, methods for element reference and assignment may be defined: ;TI"R<code>[]</code> and <code>[]=</code> 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 <code>1 + 1</code>. 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"RNote that for assignment methods the return value will be ignored when using ;TI"Dthe assignment syntax. Instead, the argument will be returned:;T@ o;;[ I"def a=(value) ;TI" return 1 + value ;TI" end ;TI" ;TI"p(self.a = 5) # prints 5 ;T;0o; ;[I"PThe actual return value will be returned when invoking the method directly:;T@ o;;[I"p send(:a=, 5) # prints 6 ;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"<<code>String#to_i</code> 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;0o; ;[I"KDefault argument values can refer to arguments that have already been ;TI"Levaluated as local variables, and argument values are always evaluated ;TI"'left to right. So this is allowed:;T@ o;;[ I""def add_values(a = 1, b = a) ;TI" a + b ;TI" end ;TI"add_values ;TI"# => 2 ;T;0o; ;[I"GBut this will raise a +NameError+ (unless there is a method named ;TI"+b+ defined):;T@ o;;[ I""def add_values(a = b, b = 1) ;TI" a + b ;TI" end ;TI"add_values ;TI"J# NameError (undefined local variable or method `b' for main:Object) ;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 <code>*</code> 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 <code>*</code> 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"AThe array argument must appear before any keyword arguments.;T@ o; ;[I"JIt is possible to gather arguments at the beginning or in the middle:;T@ o;;[ I"Bdef gather_arguments(first_arg, *middle_arguments, last_arg) ;TI" p middle_arguments ;TI" end ;TI" ;TI"1gather_arguments 1, 2, 3, 4 # prints [2, 3] ;T;0o; ;[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"&def gather_arguments(*arguments) ;TI" p arguments ;TI" end ;TI" ;TI"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 <code>*</code> 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 <code>**</code>:;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"Rorder. If an unknown keyword argument is sent by the caller, and the method ;TI"Mdoes not accept arbitrary keyword arguments, an ArgumentError is raised.;T@ o; ;[I"LTo require a specific keyword argument, do not include a default value ;TI"for the keyword argument:;T@ o;;[I"%def add_values(first:, second:) ;TI" first + second ;TI" end ;TI"add_values ;TI"7# ArgumentError (missing keywords: first, second) ;TI"%add_values(first: 1, second: 2) ;TI"# => 3 ;T;0o; ;[I"LWhen mixing keyword arguments and positional arguments, all positional ;TI"8arguments must appear before any keyword arguments.;T@ o; ;[I"MAlso, note that <code>**</code> can be used to ignore keyword arguments:;T@ o;;[I"def ignore_keywords(**) ;TI" end ;T;0o; ;[I"HTo mark a method as accepting keywords, but not actually accepting ;TI"2keywords, you can use the <code>**nil</code>:;T@ o;;[I"def no_keywords(**nil) ;TI" end ;T;0o; ;[I"KCalling such a method with keywords or a non-empty keyword splat will ;TI"Kresult in an ArgumentError. This syntax is supported so that keywords ;TI"Ocan be added to the method later without affected backwards compatibility.;T@ S; ; i;I"/Keyword and Positional Argument Separation;T@ o; ;[I"IBetween Ruby 2.0 and 2.6, keyword and positional arguments were not ;TI"Nseparated, and a keyword argument could be used as a positional argument ;TI"Iand vice-versa. In Ruby 3.0, keyword and positional arguments will ;TI"Gbe separated if the method definition includes keyword arguments. ;TI"OIn Ruby 3.0, if the method definition does not include keyword arguments, ;TI"Lkeyword arguments provided when calling the method will continue to be ;TI"1treated as a final positional hash argument.;T@ o; ;[I"HCurrently, the keyword and positional arguments are not separated, ;TI"Gbut cases where behavior will change in Ruby 3.0 will result in a ;TI"warning being emitted.;T@ o; ;[I"KThere are a few different types of keyword argument separation issues.;T@ S; ; i ;I"#Conversion of Hash to Keywords;T@ o; ;[I"GIf a method is called with the hash, the hash could be treated as ;TI"keywords:;T@ o;;[ I"def my_method(**keywords) ;TI" keywords ;TI" end ;TI"#my_method({a: 1}) # {:a => 1} ;T;0o; ;[I"KThis occurs even if the hash could be an optional positional argument ;TI"&or an element of a rest argument:;T@ o;;[I")def my_method(hash=nil, **keywords) ;TI" [hash, keywords] ;TI" end ;TI"*my_method({a: 1}) # [nil, {:a => 1}] ;TI" ;TI"&def my_method(*args, **keywords) ;TI" [args, keywords] ;TI" end ;TI")my_method({a: 1}) # [[], {:a => 1}] ;T;0o; ;[I"IHowever, if the hash is needed for a mandatory positional argument, ;TI")it would not be treated as keywords:;T@ o;;[ I"%def my_method(hash, **keywords) ;TI" [hash, keywords] ;TI" end ;TI")my_method({a: 1}) # [{:a => 1}, {}] ;T;0S; ; i ;I"3Conversion of Keywords to Positional Arguments;T@ o; ;[I"@If a method is called with keywords, but it is missing one ;TI"Bmandatory positional argument, the keywords are converted to ;TI"Ca hash and the hash used as the mandatory positional argument:;T@ o;;[ I"%def my_method(hash, **keywords) ;TI" [hash, keywords] ;TI" end ;TI"'my_method(a: 1) # [{:a => 1}, {}] ;T;0o; ;[I"0This is also true for empty keyword splats:;T@ o;;[I" kw = {} ;TI" my_method(**kw) # [{}, {}] ;T;0S; ; i ;I"/Splitting of Positional Hashes or Keywords;T@ o; ;[I"RIf a method definition accepts specific keywords and not arbitrary keywords, ;TI"Qkeywords or a positional hash may be split if the hash includes both Symbol ;TI"Qkeys and non-Symbol keys and the keywords or positional hash are not needed ;TI"Pas a mandatory positional argument. In this case, the non-Symbol keys are ;TI"Mseparated into a positional argument hash, and the Symbol keys are used ;TI"as the keyword arguments:;T@ o;;[ I"!def my_method(hash=3, a: 4) ;TI" [hash, a] ;TI" end ;TI"1my_method(a: 1, 'a' => 2) # [{"a"=>2}, 1] ;TI"1my_method({a: 1, 'a' => 2}) # [{"a"=>2}, 1] ;T;0S; ; i;I"Block Argument;T@ o; ;[I"JThe block argument is indicated by <code>&</code> 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 <code>yield</code> 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;0S; ; 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"OSimilarly, if you wish to always run code even if an exception is raised, ;TI"4you can use +ensure+ without +begin+ and +end+:;T@ o;;[ I"def my_method ;TI"* # code that may raise an exception ;TI"ensure ;TI"B # code that runs even if previous code raised an exception ;TI" end ;T;0o; ;[I"HYou can also combine +rescue+ with +ensure+ and/or +else+, without ;TI"+begin+ and +end+:;T@ o;;[I"def my_method ;TI"* # code that may raise an exception ;TI"rescue ;TI" # handle exception ;TI" else ;TI"/ # only run if no exception raised above ;TI"ensure ;TI"B # code that runs even if previous code raised an 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