ruby 2.2.4 core api reference api referenceruby 2.2.4 core api reference api reference this is the...

897
Ruby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference'.

Upload: others

Post on 05-Sep-2020

115 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ruby2.2.4CoreAPIReferenceAPIReferenceThisistheAPIdocumentationfor'Ruby2.2.4CoreAPIReferenceAPIReference'.

Page 2: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Classes/ModulesIO

IO::EAGAINWaitReadable

IO::EAGAINWaitWritable

IO::EINPROGRESSWaitReadable

IO::EINPROGRESSWaitWritable

IO::EWOULDBLOCKWaitReadable

IO::EWOULDBLOCKWaitWritable

IO::WaitReadable

IO::WaitWritable

Encoding

Encoding::CompatibilityError

Encoding::Converter

Encoding::ConverterNotFoundError

Encoding::InvalidByteSequenceError

Encoding::UndefinedConversionError

Process

Process::GID

Process::Status

Process::Sys

Process::UID

Process::Waiter

Page 3: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Enumerator

Enumerator::Generator

Enumerator::Lazy

Enumerator::Yielder

File

File::Constants

File::Stat

RubyVM

RubyVM::Env

RubyVM::InstructionSequence

Complex

Complex::compatible

GC

GC::Profiler

Math

Math::DomainError

ObjectSpace

ObjectSpace::WeakMap

Rational

Rational::compatible

ArgumentError

Array

BasicObject

Page 4: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Bignum

Binding

Class

Comparable

Continuation

Data

Dir

ENV

EOFError

EncodingError

Enumerable

Errno

Exception

FalseClass

Fiber

FiberError

FileTest

Fixnum

Float

FloatDomainError

Hash

IOError

IndexError

Page 5: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Integer

Interrupt

Kernel

KeyError

LoadError

LocalJumpError

Marshal

MatchData

Method

Module

Mutex

NameError

NilClass

NoMemoryError

NoMethodError

NotImplementedError

Numeric

Object

Proc

Random

Range

RangeError

Regexp

Page 6: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

RegexpError

Ripper

RuntimeError

ScriptError

SecurityError

Signal

SignalException

StandardError

StopIteration

String

Struct

Symbol

SyntaxError

SystemCallError

SystemExit

SystemStackError

Thread

ThreadError

ThreadGroup

Time

TracePoint

TrueClass

TypeError

Page 7: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

UnboundMethod

UncaughtThrowError

ZeroDivisionError

fatal

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 8: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classArgumentErrorRaisedwhentheargumentsarewrongandthereisn'tamorespecificExceptionclass.

Ex:passingthewrongnumberofarguments

[1,2,3].first(4,5)

raisestheexception:

ArgumentError:wrongnumberofarguments(2for1)

Ex:passinganargumentthatisnotacceptable:

[1,2,3].first(-4)

raisestheexception:

ArgumentError:negativearraysize

InFileserror.c

ParentStandardError

Page 9: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 10: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classArrayArraysareordered,integer-indexedcollectionsofanyobject.

Arrayindexingstartsat0,asinCorJava.Anegativeindexisassumedtoberelativetotheendofthearray—thatis,anindexof-1indicatesthelastelementofthearray,-2isthenexttolastelementinthearray,andsoon.

Page 11: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CreatingArrays

Anewarraycanbecreatedbyusingtheliteralconstructor[].Arrayscancontaindifferenttypesofobjects.Forexample,thearraybelowcontainsanInteger,aStringandaFloat:

ary=[1,"two",3.0]#=>[1,"two",3.0]

Anarraycanalsobecreatedbyexplicitlycalling::newwithzero,one(theinitialsizeoftheArray)ortwoarguments(theinitialsizeandadefaultobject).

ary=Array.new#=>[]

Array.new(3)#=>[nil,nil,nil]

Array.new(3,true)#=>[true,true,true]

Notethatthesecondargumentpopulatesthearraywithreferencestothesameobject.Therefore,itisonlyrecommendedincaseswhenyouneedtoinstantiatearrayswithnativelyimmutableobjectssuchasSymbols,numbers,trueorfalse.

Tocreateanarraywithseparateobjectsablockcanbepassedinstead.Thismethodissafetousewithmutableobjectssuchashashes,stringsorotherarrays:

Array.new(4){Hash.new}#=>[{},{},{},{}]

Page 12: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thisisalsoaquickwaytobuildupmulti-dimensionalarrays:

empty_table=Array.new(3){Array.new(3)}

#=>[[nil,nil,nil],[nil,nil,nil],[nil,nil,nil]]

AnarraycanalsobecreatedbyusingtheArray()method,providedbyKernel,whichtriestocallto_ary,thento_aonitsargument.

Array({:a=>"a",:b=>"b"})#=>[[:a,"a"],[:b,"b"]]

Page 13: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ExampleUsage

InadditiontothemethodsitmixesinthroughtheEnumerablemodule,theArrayclasshasproprietarymethodsforaccessing,searchingandotherwisemanipulatingarrays.

Someofthemorecommononesareillustratedbelow.

Page 14: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

AccessingElements

ElementsinanarraycanberetrievedusingtheArray#[]method.Itcantakeasingleintegerargument(anumericindex),apairofarguments(startandlength)orarange.Negativeindicesstartcountingfromtheend,with-1beingthelastelement.

arr=[1,2,3,4,5,6]

arr[2]#=>3

arr[100]#=>nil

arr[-3]#=>4

arr[2,3]#=>[3,4,5]

arr[1..4]#=>[2,3,4,5]

arr[1..-3]#=>[2,3,4]

Anotherwaytoaccessaparticulararrayelementisbyusingtheatmethod

arr.at(0)#=>1

TheslicemethodworksinanidenticalmannertoArray#[].

Toraiseanerrorforindicesoutsideofthearrayboundsorelsetoprovideadefaultvaluewhenthathappens,youcanusefetch.

arr=['a','b','c','d','e','f']

arr.fetch(100)#=>IndexError:index100outsideofarraybounds:-6...6

arr.fetch(100,"oops")#=>"oops"

Page 15: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thespecialmethodsfirstandlastwillreturnthefirstandlastelementsofanarray,respectively.

arr.first#=>1

arr.last#=>6

Toreturnthefirstnelementsofanarray,usetake

arr.take(3)#=>[1,2,3]

dropdoestheoppositeoftake,byreturningtheelementsafternelementshavebeendropped:

arr.drop(3)#=>[4,5,6]

Page 16: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ObtainingInformationaboutanArray

Arrayskeeptrackoftheirownlengthatalltimes.Toqueryanarrayaboutthenumberofelementsitcontains,uselength,countorsize.

browsers=['Chrome','Firefox','Safari','Opera'

browsers.length#=>5

browsers.count#=>5

Tocheckwhetheranarraycontainsanyelementsatall

browsers.empty?#=>false

Tocheckwhetheraparticularitemisincludedinthearray

browsers.include?('Konqueror')#=>false

Page 17: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

AddingItemstoArrays

Itemscanbeaddedtotheendofanarraybyusingeitherpushor#<<

arr=[1,2,3,4]

arr.push(5)#=>[1,2,3,4,5]

arr<<6#=>[1,2,3,4,5,6]

unshiftwilladdanewitemtothebeginningofanarray.

arr.unshift(0)#=>[0,1,2,3,4,5,6]

Withinsertyoucanaddanewelementtoanarrayatanyposition.

arr.insert(3,'apple')#=>[0,1,2,'apple',3,4,5,6]

Usingtheinsertmethod,youcanalsoinsertmultiplevaluesatonce:

arr.insert(3,'orange','pear','grapefruit')

#=>[0,1,2,"orange","pear","grapefruit","apple",3,4,5,6]

Page 18: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

RemovingItemsfromanArray

Themethodpopremovesthelastelementinanarrayandreturnsit:

arr=[1,2,3,4,5,6]

arr.pop#=>6

arr#=>[1,2,3,4,5]

Toretrieveandatthesametimeremovethefirstitem,useshift:

arr.shift#=>1

arr#=>[2,3,4,5]

Todeleteanelementataparticularindex:

arr.delete_at(2)#=>4

arr#=>[2,3,5]

Todeleteaparticularelementanywhereinanarray,usedelete:

arr=[1,2,2,3]

arr.delete(2)#=>2

arr#=>[1,3]

Ausefulmethodifyouneedtoremovenilvaluesfromanarrayiscompact:

arr=['foo',0,nil,'bar',7,'baz',nil]

arr.compact#=>['foo',0,'bar',7,'baz']

Page 19: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

arr#=>['foo',0,nil,'bar',7,'baz',nil]

arr.compact!#=>['foo',0,'bar',7,'baz']

arr#=>['foo',0,'bar',7,'baz']

Anothercommonneedistoremoveduplicateelementsfromanarray.

Ithasthenon-destructiveuniq,anddestructivemethoduniq!

arr=[2,5,6,556,6,6,8,9,0,123,556]

arr.uniq#=>[2,5,6,556,8,9,0,123]

Page 20: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

IteratingoverArrays

LikeallclassesthatincludetheEnumerablemodule,Arrayhasaneachmethod,whichdefineswhatelementsshouldbeiteratedoverandhow.IncaseofArray'seach,allelementsintheArrayinstanceareyieldedtothesuppliedblockinsequence.

Notethatthisoperationleavesthearrayunchanged.

arr=[1,2,3,4,5]

arr.each{|a|printa-=10,""}

#prints:-9-8-7-6-5

#=>[1,2,3,4,5]

Anothersometimesusefuliteratorisreverse_eachwhichwilliterateovertheelementsinthearrayinreverseorder.

words=%w[firstsecondthirdfourthfifthsixth]

str=""

words.reverse_each{|word|str+="#{word}"}

pstr#=>"sixthfifthfourththirdsecondfirst"

Themapmethodcanbeusedtocreateanewarraybasedontheoriginalarray,butwiththevaluesmodifiedbythesuppliedblock:

arr.map{|a|2*a}#=>[2,4,6,8,10]

arr#=>[1,2,3,4,5]

Page 21: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

arr.map!{|a|a**2}#=>[1,4,9,16,25]

arr#=>[1,4,9,16,25]

Page 22: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SelectingItemsfromanArray

Elementscanbeselectedfromanarrayaccordingtocriteriadefinedinablock.Theselectioncanhappeninadestructiveoranon-destructivemanner.Whilethedestructiveoperationswillmodifythearraytheywerecalledon,thenon-destructivemethodsusuallyreturnanewarraywiththeselectedelements,butleavetheoriginalarrayunchanged.

Non-destructiveSelectionarr=[1,2,3,4,5,6]

arr.select{|a|a>3}#=>[4,5,6]

arr.reject{|a|a<3}#=>[3,4,5,6]

arr.drop_while{|a|a<4}#=>[4,5,6]

arr#=>[1,2,3,4,5,6]

DestructiveSelection

select!andreject!arethecorrespondingdestructivemethodstoselectandreject

Similartoselectvs.reject,delete_ifandkeep_ifhavetheexactoppositeresultwhensuppliedwiththesameblock:

arr.delete_if{|a|a<4}#=>[4,5,6]

arr#=>[4,5,6]

arr=[1,2,3,4,5,6]

arr.keep_if{|a|a<4}#=>[1,2,3]

Page 23: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

arr#=>[1,2,3]

InFilesarray.cpack.c

ParentObject

IncludedModulesEnumerable

PublicClassMethods

Returnsanewarraypopulatedwiththegivenobjects.

Array.[](1,'a',/^A/)#=>[1,"a",/^A/]

Array[1,'a',/^A/]#=>[1,"a",/^A/]

[1,'a',/^A/]#=>[1,"a",/^A/]

Returnsanewarray.

Inthefirstform,ifnoargumentsaresent,thenewarraywillbeempty.Whenasizeandanoptionaldefaultaresent,anarrayiscreatedwithsizecopies

[](*args)

new(size=0,default=nil)new(array)new(size){|index|block}

Page 24: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ofdefault.Takenoticethatallelementswillreferencethesameobjectdefault.

Thesecondformcreatesacopyofthearraypassedasaparameter(thearrayisgeneratedbycalling#to_aryontheparameter).

first_array=["Matz","Guido"]

second_array=Array.new(first_array)#=>["Matz","Guido"]

first_array.equal?second_array#=>false

Inthelastform,anarrayofthegivensizeiscreated.Eachelementinthisarrayiscreatedbypassingtheelement'sindextothegivenblockandstoringthereturnvalue.

Array.new(3){|index|index**2}

#=>[0,1,4]

Page 25: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Whensendingthesecondparameter,thesameobjectwillbeusedasthevalueforallthearrayelements:

a=Array.new(2,Hash.new)

#=>[{},{}]

a[0]['cat']='feline'

a#=>[{"cat"=>"feline"},{"cat"=>"feline"}]

a[1]['cat']='Felix'

a#=>[{"cat"=>"Felix"},{"cat"=>"Felix"}]

SincealltheArrayelementsstorethesamehash,changestooneofthemwillaffectthemall.

Ifmultiplecopiesarewhatyouwant,youshouldusetheblockversionwhichusestheresultofthatblockeachtimeanelementofthearrayneedstobeinitialized:

a=Array.new(2){Hash.new}

a[0]['cat']='feline'

a#=>[{"cat"=>"feline"},{}]

Triestoconvertobjintoanarray,usingto_arymethod.Returnstheconvertedarrayornilifobjcannotbeconvertedforanyreason.Thismethodcanbeusedtocheckifanargumentisanarray.

Array.try_convert([1])#=>[1]

Array.try_convert("1")#=>nil

iftmp=Array.try_convert(arg)

Commongotchas

try_convert(obj)→arrayornil

Page 26: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#theargumentisanarray

elsiftmp=String.try_convert(arg)

#theargumentisastring

end

PublicInstanceMethods

SetIntersection—Returnsanewarraycontainingelementscommontothetwoarrays,excludinganyduplicates.Theorderispreservedfromtheoriginalarray.

Itcompareselementsusingtheirhashandeql?methodsforefficiency.

[1,1,3,5]&[1,2,3]#=>[1,3]

['a','b','b','z']&['a','b','c']#=>['a','b']

Seealso#uniq.

Repetition—WithaStringargument,equivalenttoary.join(str).

Otherwise,returnsanewarraybuiltbyconcatenatingtheintcopiesofself.

[1,2,3]*3#=>[1,2,3,1,2,3,1,2,3]

[1,2,3]*","#=>"1,2,3"

Concatenation—Returnsanewarraybuiltby

ary&other_ary→new_ary

ary*int→new_aryary*str→new_string

ary+other_ary→new_ary

Page 27: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

concatenatingthetwoarraystogethertoproduceathirdarray.

[1,2,3]+[4,5]#=>[1,2,3,4,5]

a=["a","b","c"]

c=a+["d","e","f"]

c#=>["a","b","c","d","e","f"]

a#=>["a","b","c"]

Notethat

x+=y

isthesameas

x=x+y

Thismeansthatitproducesanewarray.Asaconsequence,repeateduseof+=onarrayscanbequiteinefficient.

Seealso#concat.

ArrayDifference

Returnsanewarraythatisacopyoftheoriginalarray,removinganyitemsthatalsoappearinother_ary.Theorderispreservedfromtheoriginalarray.

Itcompareselementsusingtheirhashandeql?methodsforefficiency.

[1,1,2,2,3,3,4,5]-[1,2,4]#=>[3,3,5]

Ifyouneedset-likebehavior,seethelibraryclassSet.

ary-other_ary→new_ary

Page 28: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Append—Pushesthegivenobjectontotheendofthisarray.Thisexpressionreturnsthearrayitself,soseveralappendsmaybechainedtogether.

[1,2]<<"c"<<"d"<<[3,4]

#=>[1,2,"c","d",[3,4]]

Comparison—Returnsaninteger(-1,0,or+1)ifthisarrayislessthan,equalto,orgreaterthanother_ary.

Eachobjectineacharrayiscompared(usingthe<=>operator).

Arraysarecomparedinan“element-wise”manner;thefirstelementofaryiscomparedwiththefirstoneofother_aryusingthe<=>operator,theneachofthesecondelements,etc…Assoonastheresultofanysuchcomparisonisnonzero(i.e.thetwocorrespondingelementsarenotequal),thatresultisreturnedforthewholearraycomparison.

Ifalltheelementsareequal,thentheresultisbasedonacomparisonofthearraylengths.Thus,twoarraysare“equal”accordingtoArray#<=>if,andonlyif,theyhavethesamelengthandthevalueofeachelementisequaltothevalueofthecorrespondingelementintheotherarray.

nilisreturnediftheother_aryisnotanarrayorifthecomparisonoftwoelementsreturnednil.

["a","a","c"]<=>["a","b","c"]#=>-1

[1,2,3,4,5,6]<=>[1,2]#=>+1

[1,2]<=>[1,:two]#=>nil

ary<<obj→ary

ary<=>other_ary→-1,0,+1ornil

Page 29: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Equality—Twoarraysareequaliftheycontainthesamenumberofelementsandifeachelementisequalto(accordingtoObject#==)thecorrespondingelementinother_ary.

["a","c"]==["a","c",7]#=>false

["a","c",7]==["a","c",7]#=>true

["a","c",7]==["a","d","f"]#=>false

ElementReference—Returnstheelementatindex,orreturnsasubarraystartingatthestartindexandcontinuingforlengthelements,orreturnsasubarrayspecifiedbyrangeofindices.

Negativeindicescountbackwardfromtheendofthearray(-1isthelastelement).Forstartandrangecasesthestartingindexisjustbeforeanelement.Additionally,anemptyarrayisreturnedwhenthestartingindexforanelementrangeisattheendofthearray.

Returnsniliftheindex(orstartingindex)areoutofrange.

a=["a","b","c","d","e"]

a[2]+a[0]+a[1]#=>"cab"

a[6]#=>nil

a[1,2]#=>["b","c"]

a[1..3]#=>["b","c","d"]

ary==other_ary→bool

ary[index]→objornilary[start,length]→new_aryornilary[range]→new_aryornilslice(index)→objornilslice(start,length)→new_aryornilslice(range)→new_aryornil

Page 30: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a[4..7]#=>["e"]

a[6..10]#=>nil

a[-3,3]#=>["c","d","e"]

#specialcases

a[5]#=>nil

a[6,1]#=>nil

a[5,1]#=>[]

a[5..10]#=>[]

ElementAssignment—Setstheelementatindex,orreplacesasubarrayfromthestartindexforlengthelements,orreplacesasubarrayspecifiedbytherangeofindices.

Ifindicesaregreaterthanthecurrentcapacityofthearray,thearraygrowsautomatically.Elementsareinsertedintothearrayatstartiflengthiszero.

Negativeindiceswillcountbackwardfromtheendofthearray.Forstartandrangecasesthestartingindexisjustbeforeanelement.

AnIndexErrorisraisedifanegativeindexpointspastthebeginningofthearray.

Seealso#push,and#unshift.

a=Array.new

a[4]="4";#=>[nil,nil,nil,nil,"4"]

a[0,3]=['a','b','c']#=>["a","b","c",nil,"4"]

a[1..2]=[1,2]#=>["a",1,2,nil,"4"]

a[0,2]="?"#=>["?",2,nil,"4"]

a[0..2]="A"#=>["A","4"]

a[-1]="Z"#=>["A","Z"]

a[1..-1]=nil#=>["A",nil]

a[1..-1]=[]#=>["A"]

ary[index]=obj→objary[start,length]=objorother_aryornil→objorother_aryornilary[range]=objorother_aryornil→objorother_aryornil

Page 31: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a[0,0]=[1,2]#=>[1,2,"A"]

a[3,0]="B"#=>[1,2,"A","B"]

SeealsoEnumerable#any?

Searchesthroughanarraywhoseelementsarealsoarrayscomparingobjwiththefirstelementofeachcontainedarrayusingobj.==.

Returnsthefirstcontainedarraythatmatches(thatis,thefirstassociatedarray),ornilifnomatchisfound.

Seealso#rassoc

s1=["colors","red","blue","green"]

s2=["letters","a","b","c"]

s3="foo"

a=[s1,s2,s3]

a.assoc("letters")#=>["letters","a","b","c"]

a.assoc("foo")#=>nil

Returnstheelementatindex.Anegativeindexcountsfromtheendofself.Returnsniliftheindexisoutofrange.SeealsoArray#[].

a=["a","b","c","d","e"]

a.at(0)#=>"a"

a.at(-1)#=>"e"

Byusingbinarysearch,findsavaluefromthisarray

any?[{|obj|block}]→trueorfalse

assoc(obj)→new_aryornil

at(index)→objornil

bsearch{|x|block}→elem

Page 32: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

whichmeetsthegivenconditioninO(logn)wherenisthesizeofthearray.

Youcanusethismethodintwousecases:afind-minimummodeandafind-anymode.Ineithercase,theelementsofthearraymustbemonotone(orsorted)withrespecttotheblock.

Infind-minimummode(thisisagoodchoicefortypicalusecase),theblockmustreturntrueorfalse,andtheremustbeanindexi(0<=i<=ary.size)sothat:

theblockreturnsfalseforanyelementwhoseindexislessthani,and

theblockreturnstrueforanyelementwhoseindexisgreaterthanorequaltoi.

Thismethodreturnsthei-thelement.Ifiisequaltoary.size,itreturnsnil.

ary=[0,4,7,10,12]

ary.bsearch{|x|x>=4}#=>4

ary.bsearch{|x|x>=6}#=>7

ary.bsearch{|x|x>=-1}#=>0

ary.bsearch{|x|x>=100}#=>nil

Infind-anymode(thisbehaveslikelibc'sbsearch(3)),theblockmustreturnanumber,andtheremustbetwoindicesiandj(0<=i<=j<=ary.size)sothat:

theblockreturnsapositivenumberforaryif0<=k<i,

theblockreturnszeroforaryifi<=k<j,and

theblockreturnsanegativenumberforaryifj<=k<ary.size.

Underthiscondition,thismethodreturnsanyelementwhoseindexiswithini…j.Ifiisequaltoj(i.e.,thereisnoelementthatsatisfiestheblock),thismethodreturnsnil.

Page 33: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ary=[0,4,7,10,12]

#trytofindvsuchthat4<=v<8

ary.bsearch{|x|1-x/4}#=>4or7

#trytofindvsuchthat8<=v<10

ary.bsearch{|x|4-x/2}#=>nil

Youmustnotmixthetwomodesatatime;theblockmustalwaysreturneithertrue/false,oralwaysreturnanumber.Itisundefinedwhichvalueisactuallypickedupateachiteration.

Removesallelementsfromself.

a=["a","b","c","d","e"]

a.clear#=>[]

Invokesthegivenblockonceforeachelementofself.

Createsanewarraycontainingthevaluesreturnedbytheblock.

SeealsoEnumerable#collect.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

a=["a","b","c","d"]

a.collect{|x|x+"!"}#=>["a!","b!","c!","d!"]

a.map.with_index{|x,i|x*i}#=>["","b","cc","ddd"]

a#=>["a","b","c","d"]

clear→ary

collect{|item|block}→new_arymap{|item|block}→new_arycollect→Enumeratormap→Enumerator

Page 34: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Invokesthegivenblockonceforeachelementofself,replacingtheelementwiththevaluereturnedbytheblock.

SeealsoEnumerable#collect.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

a=["a","b","c","d"]

a.map!{|x|x+"!"}

a#=>["a!","b!","c!","d!"]

a.collect!.with_index{|x,i|x[0...i]}

a#=>["","b","c!","d!"]

Wheninvokedwithablock,yieldsallcombinationsoflengthnofelementsfromthearrayandthenreturnsthearrayitself.

Theimplementationmakesnoguaranteesabouttheorderinwhichthecombinationsareyielded.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Examples:

a=[1,2,3,4]

a.combination(1).to_a#=>[[1],[2],[3],[4]]

a.combination(2).to_a#=>[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

a.combination(3).to_a#=>[[1,2,3],[1,2,4],[1,3,4],[2,3,4]]

a.combination(4).to_a#=>[[1,2,3,4]]

a.combination(0).to_a#=>[[]]#onecombinationoflength0

a.combination(5).to_a#=>[]#nocombinationsoflength5

collect!{|item|block}→arymap!{|item|block}→arycollect!→Enumeratormap!→Enumerator

combination(n){|c|block}→arycombination(n)→Enumerator

Page 35: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsacopyofselfwithallnilelementsremoved.

["a",nil,"b",nil,"c",nil].compact

#=>["a","b","c"]

Removesnilelementsfromthearray.

Returnsnilifnochangesweremade,otherwisereturnsthearray.

["a",nil,"b",nil,"c"].compact!#=>["a","b","c"]

["a","b","c"].compact!#=>nil

Appendstheelementsofother_arytoself.

["a","b"].concat(["c","d"])#=>["a","b","c","d"]

a=[1,2,3]

a.concat([4,5])

a#=>[1,2,3,4,5]

SeealsoArray#+.

Returnsthenumberofelements.

Ifanargumentisgiven,countsthenumberofelementswhichequalobjusing==.

compact→new_ary

compact!→aryornil

concat(other_ary)→ary

count→intcount(obj)→intcount{|item|block}→int

Page 36: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ifablockisgiven,countsthenumberofelementsforwhichtheblockreturnsatruevalue.

ary=[1,2,4,2]

ary.count#=>4

ary.count(2)#=>2

ary.count{|x|x%2==0}#=>3

Callsthegivenblockforeachelementntimesorforeverifnilisgiven.

Doesnothingifanon-positivenumberisgivenorthearrayisempty.

Returnsniliftheloophasfinishedwithoutgettinginterrupted.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

a=["a","b","c"]

a.cycle{|x|putsx}#print,a,b,c,a,b,c,..forever.

a.cycle(2){|x|putsx}#print,a,b,c,a,b,c.

Deletesallitemsfromselfthatareequaltoobj.

Returnsthelastdeleteditem,ornilifnomatchingitemisfound.

Iftheoptionalcodeblockisgiven,theresultoftheblockisreturnediftheitemisnotfound.(Toremovenilelementsandgetaninformativereturnvalue,use#compact!)

cycle(n=nil){|obj|block}→nilcycle(n=nil)→Enumerator

delete(obj)→itemornildelete(obj){block}→itemorresultofblock

Page 37: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a=["a","b","b","b","c"]

a.delete("b")#=>"b"

a#=>["a","c"]

a.delete("z")#=>nil

a.delete("z"){"notfound"}#=>"notfound"

Deletestheelementatthespecifiedindex,returningthatelement,orniliftheindexisoutofrange.

Seealso#slice!

a=["ant","bat","cat","dog"]

a.delete_at(2)#=>"cat"

a#=>["ant","bat","dog"]

a.delete_at(99)#=>nil

Deleteseveryelementofselfforwhichblockevaluatestotrue.

Thearrayischangedinstantlyeverytimetheblockiscalled,notaftertheiterationisover.

Seealso#reject!

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

scores=[97,42,75]

scores.delete_if{|score|score<80}#=>[97]

Dropsfirstnelementsfromaryandreturnstherestoftheelementsinanarray.

delete_at(index)→objornil

delete_if{|item|block}→arydelete_if→Enumerator

drop(n)→new_ary

Page 38: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ifanegativenumberisgiven,raisesanArgumentError.

Seealso#take

a=[1,2,3,4,5,0]

a.drop(3)#=>[4,5,0]

Dropselementsupto,butnotincluding,thefirstelementforwhichtheblockreturnsnilorfalseandreturnsanarraycontainingtheremainingelements.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Seealso#take_while

a=[1,2,3,4,5,0]

a.drop_while{|i|i<3}#=>[3,4,5,0]

Callsthegivenblockonceforeachelementinself,passingthatelementasaparameter.

AnEnumeratorisreturnedifnoblockisgiven.

a=["a","b","c"]

a.each{|x|printx,"--"}

produces:

a--b--c--

drop_while{|arr|block}→new_arydrop_while→Enumerator

each{|item|block}→aryeach→Enumerator

each_index{|index|block}→aryeach_index→Enumerator

Page 39: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Sameas#each,butpassestheindexoftheelementinsteadoftheelementitself.

AnEnumeratorisreturnedifnoblockisgiven.

a=["a","b","c"]

a.each_index{|x|printx,"--"}

produces:

0--1--2--

Returnstrueifselfcontainsnoelements.

[].empty?#=>true

Returnstrueifselfandotherarethesameobject,orarebotharrayswiththesamecontent(accordingtoObject#eql?).

Triestoreturntheelementatpositionindex,butthrowsanIndexErrorexceptionifthereferencedindexliesoutsideofthearraybounds.Thiserrorcanbepreventedbysupplyingasecondargument,whichwillactasadefaultvalue.

Alternatively,ifablockisgivenitwillonlybeexecutedwhenaninvalidindexisreferenced.Negativevaluesofindexcountfromtheendofthearray.

empty?→trueorfalse

eql?(other)→trueorfalse

fetch(index)→objfetch(index,default)→objfetch(index){|index|block}→obj

Page 40: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a=[11,22,33,44]

a.fetch(1)#=>22

a.fetch(-1)#=>44

a.fetch(4,'cat')#=>"cat"

a.fetch(100){|i|puts"#{i}isoutofbounds"}

#=>"100isoutofbounds"

Thefirstthreeformssettheselectedelementsofself(whichmaybetheentirearray)toobj.

Astartofnilisequivalenttozero.

Alengthofnilisequivalenttothelengthofthearray.

Thelastthreeformsfillthearraywiththevalueofthegivenblock,whichispassedtheabsoluteindexofeachelementtobefilled.

Negativevaluesofstartcountfromtheendofthearray,where-1isthelastelement.

a=["a","b","c","d"]

a.fill("x")#=>["x","x","x","x"]

a.fill("z",2,2)#=>["x","x","z","z"]

a.fill("y",0..1)#=>["y","y","z","z"]

a.fill{|i|i*i}#=>[0,1,4,9]

a.fill(-2){|i|i*i*i}#=>[0,1,8,27]

fill(obj)→aryfill(obj,start[,length])→aryfill(obj,range)→aryfill{|index|block}→aryfill(start[,length]){|index|block}→aryfill(range){|index|block}→ary

find_index(obj)→intornilfind_index{|item|block}→intornil

Page 41: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheindexofthefirstobjectinarysuchthattheobjectis==toobj.

Ifablockisgiveninsteadofanargument,returnstheindexofthefirstobjectforwhichtheblockreturnstrue.Returnsnilifnomatchisfound.

Seealso#rindex.

AnEnumeratorisreturnedifneitherablocknorargumentisgiven.

a=["a","b","c"]

a.index("b")#=>1

a.index("z")#=>nil

a.index{|x|x=="b"}#=>1

Returnsthefirstelement,orthefirstnelements,ofthearray.Ifthearrayisempty,thefirstformreturnsnil,andthesecondformreturnsanemptyarray.Seealso#lastfortheoppositeeffect.

a=["q","r","s","t"]

a.first#=>"q"

a.first(2)#=>["q","r"]

Returnsanewarraythatisaone-dimensionalflatteningofself(recursively).

find_index→Enumeratorindex(obj)→intornilindex{|item|block}→intornilindex→Enumerator

first→objornilfirst(n)→new_ary

flatten→new_aryflatten(level)→new_ary

Page 42: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thatis,foreveryelementthatisanarray,extractitselementsintothenewarray.

Theoptionallevelargumentdeterminesthelevelofrecursiontoflatten.

s=[1,2,3]#=>[1,2,3]

t=[4,5,6,[7,8]]#=>[4,5,6,[7,8]]

a=[s,t,9,10]#=>[[1,2,3],[4,5,6,[7,8]],9,10]

a.flatten#=>[1,2,3,4,5,6,7,8,9,10]

a=[1,2,[3,[4,5]]]

a.flatten(1)#=>[1,2,3,[4,5]]

Flattensselfinplace.

Returnsnilifnomodificationsweremade(i.e.,thearraycontainsnosubarrays.)

Theoptionallevelargumentdeterminesthelevelofrecursiontoflatten.

a=[1,2,[3,[4,5]]]

a.flatten!#=>[1,2,3,4,5]

a.flatten!#=>nil

a#=>[1,2,3,4,5]

a=[1,2,[3,[4,5]]]

a.flatten!(1)#=>[1,2,3,[4,5]]

Returntrueifthisarrayisfrozen(ortemporarilyfrozenwhilebeingsorted).SeealsoObject#frozen?

Computeahash-codeforthisarray.

Twoarrayswiththesamecontentwillhavethesame

flatten!→aryornilflatten!(level)→aryornil

frozen?→trueorfalse

hash→fixnum

Page 43: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

hashcode(andwillcompareusingeql?).

SeealsoObject#hash.

Returnstrueifthegivenobjectispresentinself(thatis,ifanyelement==object),otherwisereturnsfalse.

a=["a","b","c"]

a.include?("b")#=>true

a.include?("z")#=>false

Returnstheindexofthefirstobjectinarysuchthattheobjectis==toobj.

Ifablockisgiveninsteadofanargument,returnstheindexofthefirstobjectforwhichtheblockreturnstrue.Returnsnilifnomatchisfound.

Seealso#rindex.

AnEnumeratorisreturnedifneitherablocknorargumentisgiven.

a=["a","b","c"]

a.index("b")#=>1

a.index("z")#=>nil

a.index{|x|x=="b"}#=>1

include?(object)→trueorfalse

find_index(obj)→intornilfind_index{|item|block}→intornilfind_index→Enumeratorindex(obj)→intornilindex{|item|block}→intornilindex→Enumerator

Page 44: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Replacesthecontentsofselfwiththecontentsofother_ary,truncatingorexpandingifnecessary.

a=["a","b","c","d","e"]

a.replace(["x","y","z"])#=>["x","y","z"]

a#=>["x","y","z"]

Insertsthegivenvaluesbeforetheelementwiththegivenindex.

Negativeindicescountbackwardsfromtheendofthearray,where-1isthelastelement.Ifanegativeindexisused,thegivenvalueswillbeinsertedafterthatelement,sousinganindexof-1willinsertthevaluesattheendofthearray.

a=%w{abcd}

a.insert(2,99)#=>["a","b",99,"c","d"]

a.insert(-2,1,2,3)#=>["a","b",99,"c",1,2,3,"d"]

Createsastringrepresentationofself.

["a","b","c"].to_s#=>"[\"a\",\"b\",\"c\"]"

Alsoaliasedas:to_s

Returnsastringcreatedbyconvertingeachelement

replace(other_ary)→aryinitialize_copy(other_ary)→ary

insert(index,obj...)→ary

inspect→stringto_s→string

join(separator=$,)→str

Page 45: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ofthearraytoastring,separatedbythegivenseparator.Iftheseparatorisnil,itusescurrent$,.Ifboththeseparatorand$,arenil,itusesemptystring.

["a","b","c"].join#=>"abc"

["a","b","c"].join("-")#=>"a-b-c"

Deleteseveryelementofselfforwhichthegivenblockevaluatestofalse.

Seealso#select!

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

a=%w{abcdef}

a.keep_if{|v|v=~/[aeiou]/}#=>["a","e"]

Returnsthelastelement(s)ofself.Ifthearrayisempty,thefirstformreturnsnil.

Seealso#firstfortheoppositeeffect.

a=["w","x","y","z"]

a.last#=>"z"

a.last(2)#=>["y","z"]

Returnsthenumberofelementsinself.Maybezero.

[1,2,3,4,5].length#=>5

keep_if{|item|block}→arykeep_if→Enumerator

last→objornillast(n)→new_ary

length→int

Page 46: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

[].length#=>0

Alsoaliasedas:size

Invokesthegivenblockonceforeachelementofself.

Createsanewarraycontainingthevaluesreturnedbytheblock.

SeealsoEnumerable#collect.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

a=["a","b","c","d"]

a.collect{|x|x+"!"}#=>["a!","b!","c!","d!"]

a.map.with_index{|x,i|x*i}#=>["","b","cc","ddd"]

a#=>["a","b","c","d"]

Invokesthegivenblockonceforeachelementofself,replacingtheelementwiththevaluereturnedbytheblock.

SeealsoEnumerable#collect.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

a=["a","b","c","d"]

collect{|item|block}→new_arymap{|item|block}→new_arycollect→Enumeratormap→Enumerator

collect!{|item|block}→arymap!{|item|block}→arycollect!→Enumeratormap!→Enumerator

Page 47: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a.map!{|x|x+"!"}

a#=>["a!","b!","c!","d!"]

a.collect!.with_index{|x,i|x[0...i]}

a#=>["","b","c!","d!"]

PacksthecontentsofarrintoabinarysequenceaccordingtothedirectivesinaTemplateString(seethetablebelow)Directives“A,''“a,''and“Z''maybefollowedbyacount,whichgivesthewidthoftheresultingfield.Theremainingdirectivesalsomaytakeacount,indicatingthenumberofarrayelementstoconvert.Ifthecountisanasterisk(“*''),allremainingarrayelementswillbeconverted.Anyofthedirectives“sSiIlL''maybefollowedbyanunderscore(“_'')orexclamationmark(“!'')tousetheunderlyingplatform'snativesizeforthespecifiedtype;otherwise,theyuseaplatform-independentsize.Spacesareignoredinthetemplatestring.SeealsoString#unpack.

a=["a","b","c"]

n=[65,66,67]

a.pack("A3A3A3")#=>"abc"

a.pack("a3a3a3")#=>"a\000\000b\000\000c\000\000"

n.pack("ccc")#=>"ABC"

Directivesforpack.

Integer|Array|

Directive|Element|Meaning

---------------------------------------------------------------------------

C|Integer|8-bitunsigned(unsignedchar)

S|Integer|16-bitunsigned,nativeendian(uint16_t)

L|Integer|32-bitunsigned,nativeendian(uint32_t)

Q|Integer|64-bitunsigned,nativeendian(uint64_t)

||

c|Integer|8-bitsigned(signedchar)

s|Integer|16-bitsigned,nativeendian(int16_t)

pack(aTemplateString)→aBinaryString

Page 48: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

l|Integer|32-bitsigned,nativeendian(int32_t)

q|Integer|64-bitsigned,nativeendian(int64_t)

||

S_,S!|Integer|unsignedshort,nativeendian

I,I_,I!|Integer|unsignedint,nativeendian

L_,L!|Integer|unsignedlong,nativeendian

Q_,Q!|Integer|unsignedlonglong,nativeendian(ArgumentError

||iftheplatformhasnolonglongtype.)

||(Q_andQ!isavailablesinceRuby2.1.)

||

s_,s!|Integer|signedshort,nativeendian

i,i_,i!|Integer|signedint,nativeendian

l_,l!|Integer|signedlong,nativeendian

q_,q!|Integer|signedlonglong,nativeendian(ArgumentError

||iftheplatformhasnolonglongtype.)

||(q_andq!isavailablesinceRuby2.1.)

||

S>L>Q>|Integer|sameasthedirectiveswithout">"except

s>l>q>||bigendian

S!>I!>||(availablesinceRuby1.9.3)

L!>Q!>||"S>"issameas"n"

s!>i!>||"L>"issameas"N"

l!>q!>||

||

S<L<Q<|Integer|sameasthedirectiveswithout"<"except

s<l<q<||littleendian

S!<I!<||(availablesinceRuby1.9.3)

L!<Q!<||"S<"issameas"v"

s!<i!<||"L<"issameas"V"

l!<q!<||

||

n|Integer|16-bitunsigned,network(big-endian)byteorder

N|Integer|32-bitunsigned,network(big-endian)byteorder

v|Integer|16-bitunsigned,VAX(little-endian)byteorder

V|Integer|32-bitunsigned,VAX(little-endian)byteorder

||

U|Integer|UTF-8character

w|Integer|BER-compressedinteger

Float||

Directive||Meaning

---------------------------------------------------------------------------

D,d|Float|double-precision,nativeformat

F,f|Float|single-precision,nativeformat

E|Float|double-precision,little-endianbyteorder

e|Float|single-precision,little-endianbyteorder

G|Float|double-precision,network(big-endian)byteorder

Page 49: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

g|Float|single-precision,network(big-endian)byteorder

String||

Directive||Meaning

---------------------------------------------------------------------------

A|String|arbitrarybinarystring(spacepadded,countiswidth)

a|String|arbitrarybinarystring(nullpadded,countiswidth)

Z|String|sameas``a'',exceptthatnullisaddedwith*

B|String|bitstring(MSBfirst)

b|String|bitstring(LSBfirst)

H|String|hexstring(highnibblefirst)

h|String|hexstring(lownibblefirst)

u|String|UU-encodedstring

M|String|quotedprintable,MIMEencoding(seeRFC2045)

m|String|base64encodedstring(seeRFC2045,countiswidth)

||(ifcountis0,nolinefeedareadded,seeRFC4648)

P|String|pointertoastructure(fixed-lengthstring)

p|String|pointertoanull-terminatedstring

Misc.||

Directive||Meaning

---------------------------------------------------------------------------

@|---|movestoabsoluteposition

X|---|backupabyte

x|---|nullbyte

Wheninvokedwithablock,yieldallpermutationsoflengthnoftheelementsofthearray,thenreturnthearrayitself.

Ifnisnotspecified,yieldallpermutationsofallelements.

Theimplementationmakesnoguaranteesabouttheorderinwhichthepermutationsareyielded.

Ifnoblockisgiven,anEnumeratorisreturned

permutation{|p|block}→arypermutation→Enumeratorpermutation(n){|p|block}→arypermutation(n)→Enumerator

Page 50: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

instead.

Examples:

a=[1,2,3]

a.permutation.to_a#=>[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

a.permutation(1).to_a#=>[[1],[2],[3]]

a.permutation(2).to_a#=>[[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]

a.permutation(3).to_a#=>[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

a.permutation(0).to_a#=>[[]]#onepermutationoflength0

a.permutation(4).to_a#=>[]#nopermutationsoflength4

Removesthelastelementfromselfandreturnsit,ornilifthearrayisempty.

Ifanumbernisgiven,returnsanarrayofthelastnelements(orless)justlikearray.slice!(-n,n)does.Seealso#pushfortheoppositeeffect.

a=["a","b","c","d"]

a.pop#=>"d"

a.pop(2)#=>["b","c"]

a#=>["a"]

Returnsanarrayofallcombinationsofelementsfromallarrays.

Thelengthofthereturnedarrayistheproductofthelengthofselfandtheargumentarrays.

Ifgivenablock,productwillyieldallcombinationsandreturnselfinstead.

[1,2,3].product([4,5])#=>[[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]

[1,2].product([1,2])#=>[[1,1],[1,2],[2,1],[2,2]]

pop→objornilpop(n)→new_ary

product(other_ary,...)→new_aryproduct(other_ary,...){|p|block}→ary

Page 51: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

[1,2].product([3,4],[5,6])#=>[[1,3,5],[1,3,6],[1,4,5],[1,4,6],

#[2,3,5],[2,3,6],[2,4,5],[2,4,6]]

[1,2].product()#=>[[1],[2]]

[1,2].product([])#=>[]

Append—Pushesthegivenobject(s)ontotheendofthisarray.Thisexpressionreturnsthearrayitself,soseveralappendsmaybechainedtogether.Seealso#popfortheoppositeeffect.

a=["a","b","c"]

a.push("d","e","f")

#=>["a","b","c","d","e","f"]

[1,2,3,].push(4).push(5)

#=>[1,2,3,4,5]

Searchesthroughthearraywhoseelementsarealsoarrays.

Comparesobjwiththesecondelementofeachcontainedarrayusingobj.==.

Returnsthefirstcontainedarraythatmatchesobj.

Seealso#assoc.

a=[[1,"one"],[2,"two"],[3,"three"],["ii","two"

a.rassoc("two")#=>[2,"two"]

a.rassoc("four")#=>nil

Returnsanewarraycontainingtheitemsinselfforwhichthegivenblockisnottrue.

push(obj,...)→ary

rassoc(obj)→new_aryornil

reject{|item|block}→new_aryreject→Enumerator

Page 52: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Seealso#delete_if

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Equivalentto#delete_if,deletingelementsfromselfforwhichtheblockevaluatestotrue,butreturnsnilifnochangesweremade.

Thearrayischangedinstantlyeverytimetheblockiscalled,notaftertheiterationisover.

SeealsoEnumerable#rejectand#delete_if.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Wheninvokedwithablock,yieldsallrepeatedcombinationsoflengthnofelementsfromthearrayandthenreturnsthearrayitself.

Theimplementationmakesnoguaranteesabouttheorderinwhichtherepeatedcombinationsareyielded.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Examples:

a=[1,2,3]

a.repeated_combination(1).to_a#=>[[1],[2],[3]]

a.repeated_combination(2).to_a#=>[[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]

a.repeated_combination(3).to_a#=>[[1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3],

#[1,3,3],[2,2,2],[2,2,3],[2,3,3],[3,3,3]]

a.repeated_combination(4).to_a#=>[[1,1,1,1],[1,1,1,2],[1,1,1,3],[1,1,2,2],[1,1,2,3],

#[1,1,3,3],[1,2,2,2],[1,2,2,3],[1,2,3,3],[1,3,3,3],

reject!{|item|block}→aryornilreject!→Enumerator

repeated_combination(n){|c|block}→aryrepeated_combination(n)→Enumerator

Page 53: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#[2,2,2,2],[2,2,2,3],[2,2,3,3],[2,3,3,3],[3,3,3,3]]

a.repeated_combination(0).to_a#=>[[]]#onecombinationoflength0

Wheninvokedwithablock,yieldallrepeatedpermutationsoflengthnoftheelementsofthearray,thenreturnthearrayitself.

Theimplementationmakesnoguaranteesabouttheorderinwhichtherepeatedpermutationsareyielded.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Examples:

a=[1,2]

a.repeated_permutation(1).to_a#=>[[1],[2]]

a.repeated_permutation(2).to_a#=>[[1,1],[1,2],[2,1],[2,2]]

a.repeated_permutation(3).to_a#=>[[1,1,1],[1,1,2],[1,2,1],[1,2,2],

#[2,1,1],[2,1,2],[2,2,1],[2,2,2]]

a.repeated_permutation(0).to_a#=>[[]]#onepermutationoflength0

Replacesthecontentsofselfwiththecontentsofother_ary,truncatingorexpandingifnecessary.

a=["a","b","c","d","e"]

a.replace(["x","y","z"])#=>["x","y","z"]

a#=>["x","y","z"]

Returnsanewarraycontainingself'selementsin

repeated_permutation(n){|p|block}→aryrepeated_permutation(n)→Enumerator

replace(other_ary)→aryinitialize_copy(other_ary)→ary

reverse→new_ary

Page 54: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

reverseorder.

["a","b","c"].reverse#=>["c","b","a"]

[1].reverse#=>[1]

Reversesselfinplace.

a=["a","b","c"]

a.reverse!#=>["c","b","a"]

a#=>["c","b","a"]

Sameas#each,buttraversesselfinreverseorder.

a=["a","b","c"]

a.reverse_each{|x|printx,""}

produces:

cba

Returnstheindexofthelastobjectinself==toobj.

Ifablockisgiveninsteadofanargument,returnstheindexofthefirstobjectforwhichtheblockreturnstrue,startingfromthelastobject.

Returnsnilifnomatchisfound.

Seealso#index.

Ifneitherblocknorargumentisgiven,anEnumerator

reverse!→ary

reverse_each{|item|block}→aryreverse_each→Enumerator

rindex(obj)→intornilrindex{|item|block}→intornilrindex→Enumerator

Page 55: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

isreturnedinstead.

a=["a","b","b","b","c"]

a.rindex("b")#=>3

a.rindex("z")#=>nil

a.rindex{|x|x=="b"}#=>3

Returnsanewarraybyrotatingselfsothattheelementatcountisthefirstelementofthenewarray.

Ifcountisnegativethenitrotatesintheoppositedirection,startingfromtheendofselfwhere-1isthelastelement.

a=["a","b","c","d"]

a.rotate#=>["b","c","d","a"]

a#=>["a","b","c","d"]

a.rotate(2)#=>["c","d","a","b"]

a.rotate(-3)#=>["b","c","d","a"]

Rotatesselfinplacesothattheelementatcountcomesfirst,andreturnsself.

Ifcountisnegativethenitrotatesintheoppositedirection,startingfromtheendofthearraywhere-1isthelastelement.

a=["a","b","c","d"]

a.rotate!#=>["b","c","d","a"]

a#=>["b","c","d","a"]

a.rotate!(2)#=>["d","a","b","c"]

a.rotate!(-3)#=>["a","b","c","d"]

rotate(count=1)→new_ary

rotate!(count=1)→ary

sample→objsample(random:rng)→obj

Page 56: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Choosearandomelementornrandomelementsfromthearray.

Theelementsarechosenbyusingrandomanduniqueindicesintothearrayinordertoensurethatanelementdoesn'trepeatitselfunlessthearrayalreadycontainedduplicateelements.

Ifthearrayisemptythefirstformreturnsnilandthesecondformreturnsanemptyarray.

Theoptionalrngargumentwillbeusedastherandomnumbergenerator.

a=[1,2,3,4,5,6,7,8,9,10]

a.sample#=>7

a.sample(4)#=>[6,4,2,5]

Returnsanewarraycontainingallelementsofaryforwhichthegivenblockreturnsatruevalue.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

[1,2,3,4,5].select{|num|num.even?}#=>[2,4]

a=%w{abcdef}

a.select{|v|v=~/[aeiou]/}#=>["a","e"]

SeealsoEnumerable#select.

sample(n)→new_arysample(n,random:rng)→new_ary

select{|item|block}→new_aryselect→Enumerator

select!{|item|block}→aryornilselect!→Enumerator

Page 57: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Invokesthegivenblockpassinginsuccessiveelementsfromself,deletingelementsforwhichtheblockreturnsafalsevalue.

Ifchangesweremade,itwillreturnself,otherwiseitreturnsnil.

Seealso#keep_if

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Removesthefirstelementofselfandreturnsit(shiftingallotherelementsdownbyone).Returnsnilifthearrayisempty.

Ifanumbernisgiven,returnsanarrayofthefirstnelements(orless)justlikearray.slice!(0,n)does.Witharycontainingonlytheremainderelements,notincludingwhatwasshiftedtonew_ary.Seealso#unshiftfortheoppositeeffect.

args=["-m","-q","filename"]

args.shift#=>"-m"

args#=>["-q","filename"]

args=["-m","-q","filename"]

args.shift(2)#=>["-m","-q"]

args#=>["filename"]

Returnsanewarraywithelementsofselfshuffled.

a=[1,2,3]#=>[1,2,3]

a.shuffle#=>[2,3,1]

shift→objornilshift(n)→new_ary

shuffle→new_aryshuffle(random:rng)→new_ary

Page 58: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a#=>[1,2,3]

Theoptionalrngargumentwillbeusedastherandomnumbergenerator.

a.shuffle(random:Random.new(1))#=>[1,3,2]

Shuffleselementsinselfinplace.

a=[1,2,3]#=>[1,2,3]

a.shuffle!#=>[2,3,1]

a#=>[2,3,1]

Theoptionalrngargumentwillbeusedastherandomnumbergenerator.

a.shuffle!(random:Random.new(1))#=>[1,3,2]

Aliasfor:length

ElementReference—Returnstheelementatindex,orreturnsasubarraystartingatthestartindexandcontinuingforlengthelements,orreturnsasubarrayspecifiedbyrangeofindices.

shuffle!→aryshuffle!(random:rng)→ary

size()

ary[index]→objornilary[start,length]→new_aryornilary[range]→new_aryornilslice(index)→objornilslice(start,length)→new_aryornilslice(range)→new_aryornil

Page 59: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Negativeindicescountbackwardfromtheendofthearray(-1isthelastelement).Forstartandrangecasesthestartingindexisjustbeforeanelement.Additionally,anemptyarrayisreturnedwhenthestartingindexforanelementrangeisattheendofthearray.

Returnsniliftheindex(orstartingindex)areoutofrange.

a=["a","b","c","d","e"]

a[2]+a[0]+a[1]#=>"cab"

a[6]#=>nil

a[1,2]#=>["b","c"]

a[1..3]#=>["b","c","d"]

a[4..7]#=>["e"]

a[6..10]#=>nil

a[-3,3]#=>["c","d","e"]

#specialcases

a[5]#=>nil

a[6,1]#=>nil

a[5,1]#=>[]

a[5..10]#=>[]

Deletestheelement(s)givenbyanindex(optionallyuptolengthelements)orbyarange.

Returnsthedeletedobject(orobjects),orniliftheindexisoutofrange.

a=["a","b","c"]

a.slice!(1)#=>"b"

a#=>["a","c"]

a.slice!(-1)#=>"c"

a#=>["a"]

a.slice!(100)#=>nil

a#=>["a"]

slice!(index)→objornilslice!(start,length)→new_aryornilslice!(range)→new_aryornil

Page 60: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanewarraycreatedbysortingself.

Comparisonsforthesortwillbedoneusingthe<=>operatororusinganoptionalcodeblock.

Theblockmustimplementacomparisonbetweenaandb,andreturn-1,whenafollowsb,0whenaandbareequivalent,or+1ifbfollowsa.

SeealsoEnumerable#sort_by.

a=["d","a","e","c","b"]

a.sort#=>["a","b","c","d","e"]

a.sort{|x,y|y<=>x}#=>["e","d","c","b","a"]

Sortsselfinplace.

Comparisonsforthesortwillbedoneusingthe<=>operatororusinganoptionalcodeblock.

Theblockmustimplementacomparisonbetweenaandb,andreturn-1,whenafollowsb,0whenaandbareequivalent,or+1ifbfollowsa.

SeealsoEnumerable#sort_by.

a=["d","a","e","c","b"]

a.sort!#=>["a","b","c","d","e"]

a.sort!{|x,y|y<=>x}#=>["e","d","c","b","a"]

sort→new_arysort{|a,b|block}→new_ary

sort!→arysort!{|a,b|block}→ary

sort_by!{|obj|block}→ary

Page 61: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Sortsselfinplaceusingasetofkeysgeneratedbymappingthevaluesinselfthroughthegivenblock.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Returnsfirstnelementsfromthearray.

Ifanegativenumberisgiven,raisesanArgumentError.

Seealso#drop

a=[1,2,3,4,5,0]

a.take(3)#=>[1,2,3]

Passeselementstotheblockuntiltheblockreturnsnilorfalse,thenstopsiteratingandreturnsanarrayofallpriorelements.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Seealso#drop_while

a=[1,2,3,4,5,0]

a.take_while{|i|i<3}#=>[1,2]

Returnsself.

IfcalledonasubclassofArray,convertsthereceivertoanArrayobject.

sort_by!→Enumerator

take(n)→new_ary

take_while{|arr|block}→new_arytake_while→Enumerator

to_a→ary

Page 62: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsself.

Returnstheresultofinterpretingaryasanarrayof[key,value]pairs.

[[:foo,:bar],[1,2]].to_h

#=>{:foo=>:bar,1=>2}

Aliasfor:inspect

Assumesthatselfisanarrayofarraysandtransposestherowsandcolumns.

a=[[1,2],[3,4],[5,6]]

a.transpose#=>[[1,3,5],[2,4,6]]

Ifthelengthofthesubarraysdon'tmatch,anIndexErrorisraised.

Returnsanewarraybyremovingduplicatevaluesinself.

Ifablockisgiven,itwillusethereturnvalueoftheblockforcomparison.

Itcomparesvaluesusingtheirhashandeql?methodsforefficiency.

a=["a","a","b","b","c"]

to_ary→ary

to_h→hash

to_s()

transpose→new_ary

uniq→new_aryuniq{|item|...}→new_ary

Page 63: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a.uniq#=>["a","b","c"]

b=[["student","sam"],["student","george"],["teacher"

b.uniq{|s|s.first}#=>[["student","sam"],["teacher","matz"]]

Removesduplicateelementsfromself.

Ifablockisgiven,itwillusethereturnvalueoftheblockforcomparison.

Itcomparesvaluesusingtheirhashandeql?methodsforefficiency.

Returnsnilifnochangesaremade(thatis,noduplicatesarefound).

a=["a","a","b","b","c"]

a.uniq!#=>["a","b","c"]

b=["a","b","c"]

b.uniq!#=>nil

c=[["student","sam"],["student","george"],["teacher"

c.uniq!{|s|s.first}#=>[["student","sam"],["teacher","matz"]]

Prependsobjectstothefrontofself,movingotherelementsupwards.Seealso#shiftfortheoppositeeffect.

a=["b","c","d"]

a.unshift("a")#=>["a","b","c","d"]

a.unshift(1,2)#=>[1,2,"a","b","c","d"]

uniq!→aryorniluniq!{|item|...}→aryornil

unshift(obj,...)→ary

Page 64: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanarraycontainingtheelementsinselfcorrespondingtothegivenselector(s).

Theselectorsmaybeeitherintegerindicesorranges.

Seealso#select.

a=%w{abcdef}

a.values_at(1,3,5)#=>["b","d","f"]

a.values_at(1,3,5,7)#=>["b","d","f",nil]

a.values_at(-1,-2,-2,-7)#=>["f","e","e",nil]

a.values_at(4..6,3...6)#=>["e","f",nil,"d","e","f"]

Convertsanyargumentstoarrays,thenmergeselementsofselfwithcorrespondingelementsfromeachargument.

Thisgeneratesasequenceofary.sizen-elementarrays,wherenisonemorethanthecountofarguments.

Ifthesizeofanyargumentislessthanthesizeoftheinitialarray,nilvaluesaresupplied.

Ifablockisgiven,itisinvokedforeachoutputarray,otherwiseanarrayofarraysisreturned.

a=[4,5,6]

b=[7,8,9]

[1,2,3].zip(a,b)#=>[[1,4,7],[2,5,8],[3,6,9]]

[1,2].zip(a,b)#=>[[1,4,7],[2,5,8]]

a.zip([1,2],[8])#=>[[4,1,8],[5,2,nil],[6,nil,nil]]

values_at(selector,...)→new_ary

zip(arg,...)→new_aryzip(arg,...){|arr|block}→nil

Page 65: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SetUnion—Returnsanewarraybyjoiningarywithother_ary,excludinganyduplicatesandpreservingtheorderfromtheoriginalarray.

Itcompareselementsusingtheirhashandeql?methodsforefficiency.

["a","b","c"]|["c","d","a"]#=>["a","b","c","d"]

Seealso#uniq.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

ary|other_ary→new_ary

Page 66: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classBasicObjectBasicObjectistheparentclassofallclassesinRuby.It'sanexplicitblankclass.

BasicObjectcanbeusedforcreatingobjecthierarchiesindependentofRuby'sobjecthierarchy,proxyobjectsliketheDelegatorclass,orotheruseswherenamespacepollutionfromRuby'smethodsandclassesmustbeavoided.

ToavoidpollutingBasicObjectforotherusersanappropriatelynamedsubclassofBasicObjectshouldbecreatedinsteadofdirectlymodifyingBasicObject:

classMyObjectSystem<BasicObject

end

BasicObjectdoesnotincludeKernel(formethodslikeputs)andBasicObjectisoutsideofthenamespaceofthestandardlibrarysocommonclasseswillnotbefoundwithoutusingafullclasspath.

AvarietyofstrategiescanbeusedtoprovideusefulportionsofthestandardlibrarytosubclassesofBasicObject.AsubclasscouldincludeKerneltoobtainputs,exit,etc.AcustomKernel-likemodulecouldbecreatedandincludedordelegationcanbeusedvia

Page 67: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

method_missing:

classMyObjectSystem<BasicObject

DELEGATE=[:puts,:p]

defmethod_missing(name,*args,&block)

superunlessDELEGATE.include?name

::Kernel.send(name,*args,&block)

end

defrespond_to_missing?(name,include_private=

DELEGATE.include?(name)orsuper

end

end

AccesstoclassesandmodulesfromtheRubystandardlibrarycanbeobtainedinaBasicObjectsubclassbyreferencingthedesiredconstantfromtherootlike::Fileor::Enumerator.Likemethod_missing,const_missingcanbeusedtodelegateconstantlookuptoObject:

classMyObjectSystem<BasicObject

defself.const_missing(name)

::Object.const_get(name)

end

end

InFilesclass.cgc.cobject.cvm_eval.c

Page 68: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Parent

PublicClassMethods

Notdocumented

PublicInstanceMethods

Booleannegate.

Returnstrueiftwoobjectsarenot-equal,otherwisefalse.

Equality—AttheObjectlevel,==returnstrueonlyifobjandotherarethesameobject.Typically,thismethodisoverriddenindescendantclassestoprovideclass-specificmeaning.

Unlike==,theequal?methodshouldneverbeoverriddenbysubclassesasitisusedtodetermineobjectidentity(thatis,a.equal?(b)ifandonlyifaisthesameobjectasb):

obj="a"

other=obj.dup

new()

!obj→trueorfalse

obj!=other→trueorfalse

obj==other→trueorfalseequal?(other)→trueorfalseeql?(other)→trueorfalse

Page 69: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

obj==other#=>true

obj.equal?other#=>false

obj.equal?obj#=>true

Theeql?methodreturnstrueifobjandotherrefertothesamehashkey.ThisisusedbyHashtotestmembersforequality.ForobjectsofclassObject,eql?issynonymouswith==.Subclassesnormallycontinuethistraditionbyaliasingeql?totheiroverridden==method,butthereareexceptions.Numerictypes,forexample,performtypeconversionacross==,butnotacrosseql?,so:

1==1.0#=>true

1.eql?1.0#=>false

Returnsanintegeridentifierforobj.

Thesamenumberwillbereturnedonallcallstoobject_idforagivenobject,andnotwoactiveobjectswillshareanid.

Note:thatsomeobjectsofbuiltinclassesarereusedforoptimization.Thisisthecaseforimmediatevaluesandfrozenstringliterals.

Immediatevaluesarenotpassedbyreferencebutarepassedbyvalue:nil,true,false,Fixnums,Symbols,andsomeFloats.

Object.new.object_id==Object.new.object_id#=>false

(21*2).object_id==(21*2).object_id#=>true

"hello".object_id=="hello".object_id#=>false

"hi".freeze.object_id=="hi".freeze.object_id#=>true

__id__→integerobject_id→integer

Page 70: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Invokesthemethodidentifiedbysymbol,passingitanyargumentsspecified.Youcanuse__send__ifthenamesendclasheswithanexistingmethodinobj.Whenthemethodisidentifiedbyastring,thestringisconvertedtoasymbol.

classKlass

defhello(*args)

"Hello"+args.join('')

end

end

k=Klass.new

k.send:hello,"gentle","readers"#=>"Hellogentlereaders"

Equality—AttheObjectlevel,==returnstrueonlyifobjandotherarethesameobject.Typically,thismethodisoverriddenindescendantclassestoprovideclass-specificmeaning.

Unlike==,theequal?methodshouldneverbeoverriddenbysubclassesasitisusedtodetermineobjectidentity(thatis,a.equal?(b)ifandonlyifaisthesameobjectasb):

obj="a"

other=obj.dup

obj==other#=>true

obj.equal?other#=>false

obj.equal?obj#=>true

send(symbol[,args...])→obj__send__(symbol[,args...])→objsend(string[,args...])→obj__send__(string[,args...])→obj

obj==other→trueorfalseequal?(other)→trueorfalseeql?(other)→trueorfalse

Page 71: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Theeql?methodreturnstrueifobjandotherrefertothesamehashkey.ThisisusedbyHashtotestmembersforequality.ForobjectsofclassObject,eql?issynonymouswith==.Subclassesnormallycontinuethistraditionbyaliasingeql?totheiroverridden==method,butthereareexceptions.Numerictypes,forexample,performtypeconversionacross==,butnotacrosseql?,so:

1==1.0#=>true

1.eql?1.0#=>false

EvaluatesastringcontainingRubysourcecode,orthegivenblock,withinthecontextofthereceiver(obj).Inordertosetthecontext,thevariableselfissettoobjwhilethecodeisexecuting,givingthecodeaccesstoobj'sinstancevariablesandprivatemethods.

Wheninstance_evalisgivenablock,objisalsopassedinastheblock'sonlyargument.

Wheninstance_evalisgivenaString,theoptionalsecondandthirdparameterssupplyafilenameandstartinglinenumberthatareusedwhenreportingcompilationerrors.

classKlassWithSecret

definitialize

@secret=99

end

private

defthe_secret

"Ssssh!Thesecretis#{@secret}."

instance_eval(string[,filename[,lineno]])→objinstance_eval{|obj|block}→obj

Page 72: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

end

k=KlassWithSecret.new

k.instance_eval{@secret}#=>99

k.instance_eval{the_secret}#=>"Ssssh!Thesecretis99."

k.instance_eval{|obj|obj==self}#=>true

Executesthegivenblockwithinthecontextofthereceiver(obj).Inordertosetthecontext,thevariableselfissettoobjwhilethecodeisexecuting,givingthecodeaccesstoobj'sinstancevariables.Argumentsarepassedasblockparameters.

classKlassWithSecret

definitialize

@secret=99

end

end

k=KlassWithSecret.new

k.instance_exec(5){|x|@secret+x}#=>104

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

instance_exec(arg...){|var...|block}→obj

Page 73: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classBignumBignumobjectsholdintegersoutsidetherangeofFixnum.BignumobjectsarecreatedautomaticallywhenintegercalculationswouldotherwiseoverflowaFixnum.WhenacalculationinvolvingBignumobjectsreturnsaresultthatwillfitinaFixnum,theresultisautomaticallyconverted.

Forthepurposesofthebitwiseoperationsand[],aBignumistreatedasifitwereaninfinite-lengthbitstringwith2'scomplementrepresentation.

WhileFixnumvaluesareimmediate,Bignumobjectsarenot—assignmentandparameterpassingworkwithreferencestoobjects,nottheobjectsthemselves.

InFilesbignum.c

ParentInteger

Constants

Page 74: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GMP_VERSION

TheversionofloadedGMP.

PublicInstanceMethods

Returnsbigmoduloother.SeeNumeric#divmodformoreinformation.

Performsbitwiseandbetweenbigandnumeric.

Multipliesbigandother,returningtheresult.

Raisesbigtotheexponentpower(whichmaybeaninteger,float,oranythingthatwillcoercetoanumber).TheresultmaybeaFixnum,Bignum,orFloat

123456789**2#=>15241578750190521

123456789**1.2#=>5126464716.09932

123456789**-2#=>6.5610001194102e-17

Addsbigandother,returningtheresult.

big%other→Numericmodulo(other)→Numeric

big&numeric→integer

big*other→Numeric

big**exponent→numeric

big+other→Numeric

big-other→Numeric

Page 75: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Subtractsotherfrombig,returningtheresult.

Unaryminus(returnsanintegerwhosevalueis0-big)

Performsdivision:theclassoftheresultingobjectdependsontheclassofnumericandonthemagnitudeoftheresult.

Returnstrueifthevalueofbigislessthanthatofreal.

Shiftsbigleftnumericpositions(rightifnumericisnegative).

Returnstrueifthevalueofbigislessthanorequaltothatofreal.

Comparison—Returns-1,0,or+1dependingonwhetherbigislessthan,equalto,orgreaterthannumeric.ThisisthebasisforthetestsinComparable.

nilisreturnedifthetwovaluesareincomparable.

-big→integer

big/other→Numeric

big<real→trueorfalse

big<<numeric→integer

big<=real→trueorfalse

big<=>numeric→-1,0,+1ornil

big==obj→trueorfalse

Page 76: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueonlyifobjhasthesamevalueasbig.ContrastthiswithBignum#eql?,whichrequiresobjtobeaBignum.

68719476736==68719476736.0#=>true

Returnstrueonlyifobjhasthesamevalueasbig.ContrastthiswithBignum#eql?,whichrequiresobjtobeaBignum.

68719476736==68719476736.0#=>true

Returnstrueifthevalueofbigisgreaterthanthatofreal.

Returnstrueifthevalueofbigisgreaterthanorequaltothatofreal.

Shiftsbigrightnumericpositions(leftifnumericisnegative).

BitReference—Returnsthenthbitinthe(assumed)binaryrepresentationofbig,wherebigistheleastsignificantbit.

a=9**15

50.downto(0)do|n|

big==obj→trueorfalse

big>real→trueorfalse

big>=real→trueorfalse

big>>numeric→integer

big[n]→0,1

Page 77: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

printa[n]

end

produces:

000101110110100000111000011110010100111100010111001

Performsbitwise+exclusiveor+betweenbigandnumeric.

Returnstheabsolutevalueofbig.

-1234567890987654321.abs#=>1234567890987654321

Returnsthenumberofbitsofthevalueofint.

“thenumberofbits”meansthatthebitpositionofthehighestbitwhichisdifferenttothesignbit.(Thebitpositionofthebit2**nisn+1.)Ifthereisnosuchbit(zeroorminusone),zeroisreturned.

I.e.Thismethodreturnsceil(log2(int<0?-int:int+1)).

(-2**10000-1).bit_length#=>10001

(-2**10000).bit_length#=>10000

(-2**10000+1).bit_length#=>10000

(-2**1000-1).bit_length#=>1001

(-2**1000).bit_length#=>1000

(-2**1000+1).bit_length#=>1000

(2**1000-1).bit_length#=>1000

big^numeric→integer

abs→aBignummagnitude→aBignum

bit_length→integer

Page 78: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(2**1000).bit_length#=>1001

(2**1000+1).bit_length#=>1001

(2**10000-1).bit_length#=>10000

(2**10000).bit_length#=>10001

(2**10000+1).bit_length#=>10001

ThismethodcanbeusedtodetectoverflowinArray#packasfollows.

ifn.bit_length<32

[n].pack("l")#nooverflow

else

raise"overflow"

end

ReturnsanarraywithbothanumericandabigrepresentedasBignumobjects.

ThisisachievedbyconvertingnumerictoaBignum.

ATypeErrorisraisedifthenumericisnotaFixnumorBignumtype.

(0x3FFFFFFFFFFFFFFF+1).coerce(42)#=>[42,4611686018427387904]

Performsintegerdivision:returnsintegervalue.

SeeNumeric#divmod.

ReturnstrueonlyifobjisaBignumwiththesamevalueasbig.ContrastthiswithBignum#==,which

coerce(numeric)→array

div(other)→integer

divmod(numeric)→array

eql?(obj)→trueorfalse

Page 79: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

performstypeconversions.

68719476736.eql?(68719476736.0)#=>false

Returnstrueifbigisanevennumber.

Returnsthefloatingpointresultofdividingbigbynumeric.

-1234567890987654321.fdiv(13731)#=>-89910996357705.5

-1234567890987654321.fdiv(13731.24)#=>-89909424858035.7

Computeahashbasedonthevalueofbig.

SeealsoObject#hash.

Aliasfor:to_s

Returnstheabsolutevalueofbig.

-1234567890987654321.abs#=>1234567890987654321

Returnsbigmoduloother.SeeNumeric#divmodfor

even?→trueorfalse

fdiv(numeric)→float

hash→fixnum

inspect(p1=v1)

abs→aBignummagnitude→aBignum

big%other→Numericmodulo(other)→Numeric

Page 80: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moreinformation.

Returnstrueifbigisanoddnumber.

Returnstheremainderafterdividingbigbynumeric.

-1234567890987654321.remainder(13731)#=>-6966

-1234567890987654321.remainder(13731.24)#=>-9906.22531493148

Returnsthenumberofbytesinthemachinerepresentationofbig.

(256**10-1).size#=>12

(256**20-1).size#=>20

(256**40-1).size#=>40

ConvertsbigtoaFloat.Ifbigdoesn'tfitinaFloat,theresultisinfinity.

Returnsastringcontainingtherepresentationofbigradixbase(2through36).

12345654321.to_s#=>"12345654321"

12345654321.to_s(2)#=>"1011011111110110111011110000110001"

12345654321.to_s(8)#=>"133766736061"

12345654321.to_s(16)#=>"2dfdbbc31"

78546939656932.to_s(36)#=>"rubyrules"

odd?→trueorfalse

remainder(numeric)→number

size→integer

to_f→float

to_s(base=10)→string

Page 81: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Alsoaliasedas:inspect

Performsbitwiseorbetweenbigandnumeric.

Invertsthebitsinbig.AsBignumsareconceptuallyinfinitelength,theresultactsasifithadaninfinitenumberofonebitstotheleft.Inhexrepresentations,thisisdisplayedastwoperiodstotheleftofthedigits.

sprintf("%X",~0x1122334455)#=>"..FEEDDCCBBAA"

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

big|numeric→integer

~big→integer

Page 82: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classBindingObjectsofclassBindingencapsulatetheexecutioncontextatsomeparticularplaceinthecodeandretainthiscontextforfutureuse.Thevariables,methods,valueofself,andpossiblyaniteratorblockthatcanbeaccessedinthiscontextareallretained.BindingobjectscanbecreatedusingKernel#binding,andaremadeavailabletothecallbackofKernel#set_trace_func.

ThesebindingobjectscanbepassedasthesecondargumentoftheKernel#evalmethod,establishinganenvironmentfortheevaluation.

classDemo

definitialize(n)

@secret=n

end

defget_binding

returnbinding()

end

end

k1=Demo.new(99)

b1=k1.get_binding

k2=Demo.new(-3)

b2=k2.get_binding

eval("@secret",b1)#=>99

eval("@secret",b2)#=>-3

eval("@secret")#=>nil

Page 83: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Bindingobjectshavenoclass-specificmethods.

InFilesproc.c

ParentObject

PublicInstanceMethods

EvaluatestheRubyexpression(s)instring,inthebinding'scontext.Iftheoptionalfilenameandlinenoparametersarepresent,theywillbeusedwhenreportingsyntaxerrors.

defget_binding(param)

returnbinding

end

b=get_binding("hello")

b.eval("param")#=>"hello"

Returnsatrueifalocalvariablesymbolexists.

deffoo

a=1

binding.local_variable_defined?(:a)#=>true

binding.local_variable_defined?(:b)#=>false

end

Thismethodisshortversionofthefollowingcode.

binding.eval("defined?(#{symbol})=='local-variable'")

eval(string[,filename[,lineno]])→obj

local_variable_defined?(symbol)→obj

Page 84: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsavalueoflocalvariablesymbol.

deffoo

a=1

binding.local_variable_get(:a)#=>1

binding.local_variable_get(:b)#=>NameError

end

Thismethodisshortversionofthefollowingcode.

binding.eval("#{symbol}")

Setlocalvariablenamedsymbolasobj.

deffoo

a=1

b=binding

b.local_variable_set(:a,2)#setexistinglocalvariable`a'

b.local_variable_set(:b,3)#createnewlocalvariable`b'

#`b'existsonlyinbinding.

b.local_variable_get(:a)#=>2

b.local_variable_get(:b)#=>3

pa#=>2

pb#=>NameError

end

Thismethodisasimilarbehaviorofthefollowingcode

binding.eval("#{symbol}=#{obj}")

ifobjcanbedumpedinRubycode.

Returnsthesymbolnamesofthebinding'slocal

local_variable_get(symbol)→obj

local_variable_set(symbol,obj)→obj

local_variables→Array

Page 85: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

variables

deffoo

a=1

2.timesdo|n|

binding.local_variables#=>[:a,:n]

end

end

Thismethodisshortversionofthefollowingcode.

binding.eval("local_variables")

Returnstheboundreceiverofthebindingobject.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

receiver→object

Page 86: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classClassClassesinRubyarefirst-classobjects—eachisaninstanceofclassClass.

Typically,youcreateanewclassbyusing:

className

#somecodedescribingtheclassbehavior

end

Whenanewclassiscreated,anobjectoftypeClassisinitializedandassignedtoaglobalconstant(Nameinthiscase).

WhenName.newiscalledtocreateanewobject,thenewmethodinClassisrunbydefault.ThiscanbedemonstratedbyoverridingnewinClass:

classClass

aliasold_newnew

defnew(*args)

print"Creatinganew",self.name,"\n"

old_new(*args)

end

end

className

end

n=Name.new

produces:

Page 87: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CreatinganewName

Classes,modules,andobjectsareinterrelated.Inthediagramthatfollows,theverticalarrowsrepresentinheritance,andtheparenthesesmetaclasses.Allmetaclassesareinstancesoftheclass`Class'.

+---------++-...

|||

BasicObject-----|-->(BasicObject)-------|-...

^|^|

||||

Object---------|----->(Object)---------|-...

^|^|

||||

+-------+|+--------+|

||||||

|Module-|---------|--->(Module)-|-...

|^||^|

||||||

|Class-|---------|---->(Class)-|-...

|^||^|

|+---+|+----+

||

obj--->OtherClass---------->(OtherClass)-----------...

InFilesclass.cobject.c

ParentModule

Page 88: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PublicClassMethods

Createsanewanonymous(unnamed)classwiththegivensuperclass(orObjectifnoparameterisgiven).Youcangiveaclassanamebyassigningtheclassobjecttoaconstant.

Ifablockisgiven,itispassedtheclassobject,andtheblockisevaluatedinthecontextofthisclassusingclass_eval.

fred=Class.newdo

defmeth1

"hello"

end

defmeth2

"bye"

end

end

a=fred.new#=>#<#<Class:0x100381890>:0x100376b98>

a.meth1#=>"hello"

a.meth2#=>"bye"

Assigntheclasstoaconstant(namestartinguppercase)ifyouwanttotreatitlikearegularclass.

PublicInstanceMethods

Allocatesspaceforanewobjectofclass'sclassanddoesnotcallinitializeonthenewinstance.Thereturnedobjectmustbeaninstanceofclass.

new(super_class=Object)→a_classnew(super_class=Object){|mod|...}→a_class

allocate()→obj

Page 89: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

klass=Class.newdo

definitialize(*args)

@initialized=true

end

definitialized?

@initialized||false

end

end

klass.allocate.initialized?#=>false

Callsallocatetocreateanewobjectofclass'sclass,theninvokesthatobject'sinitializemethod,passingitargs.Thisisthemethodthatendsupgettingcalledwheneveranobjectisconstructedusing.new.

Returnsthesuperclassofclass,ornil.

File.superclass#=>IO

IO.superclass#=>Object

Object.superclass#=>BasicObject

classFoo;end

classBar<Foo;end

Bar.superclass#=>Foo

Returnsnilwhenthegivenclassdoesnothaveaparentclass:

BasicObject.superclass#=>nil

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

new(args,...)→obj

superclass→a_super_classornil

Page 90: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleComparableTheComparablemixinisusedbyclasseswhoseobjectsmaybeordered.Theclassmustdefinethe<=>operator,whichcomparesthereceiveragainstanotherobject,returning-1,0,or+1dependingonwhetherthereceiverislessthan,equalto,orgreaterthantheotherobject.Iftheotherobjectisnotcomparablethenthe<=>operatorshouldreturnnil.Comparableuses<=>toimplementtheconventionalcomparisonoperators(<,<=,==,>=,and>)andthemethodbetween?.

classSizeMatters

includeComparable

attr:str

def<=>(anOther)

str.size<=>anOther.str.size

end

definitialize(str)

@str=str

end

definspect

@str

end

end

s1=SizeMatters.new("Z")

s2=SizeMatters.new("YY")

s3=SizeMatters.new("XXX")

s4=SizeMatters.new("WWWW")

s5=SizeMatters.new("VVVVV")

s1<s2#=>true

Page 91: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

s4.between?(s1,s3)#=>false

s4.between?(s3,s5)#=>true

[s3,s2,s5,s4,s1].sort#=>[Z,YY,XXX,WWWW,VVVVV]

InFilescompar.c

PublicInstanceMethods

Comparestwoobjectsbasedonthereceiver's<=>method,returningtrueifitreturns-1.

Comparestwoobjectsbasedonthereceiver's<=>method,returningtrueifitreturns-1or0.

Comparestwoobjectsbasedonthereceiver's<=>method,returningtrueifitreturns0.Alsoreturnstrueifobjandotherarethesameobject.

Evenifobj<=>otherraisedanexception,theexceptionisignoredandreturnsfalse.

Comparestwoobjectsbasedonthereceiver's<=>method,returningtrueifitreturns1.

obj<other→trueorfalse

obj<=other→trueorfalse

obj==other→trueorfalse

obj>other→trueorfalse

Page 92: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Comparestwoobjectsbasedonthereceiver's<=>method,returningtrueifitreturns0or1.

Returnsfalseifobj<=>minislessthanzeroorifanObject<=>maxisgreaterthanzero,trueotherwise.

3.between?(1,5)#=>true

6.between?(1,5)#=>false

'cat'.between?('ant','dog')#=>true

'gnu'.between?('ant','dog')#=>false

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

obj>=other→trueorfalse

between?(min,max)→trueorfalse

Page 93: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classComplexAcomplexnumbercanberepresentedasapairedrealnumberwithimaginaryunit;a+bi.Whereaisrealpart,bisimaginarypartandiisimaginaryunit.Realaequalscomplexa+0imathematically.

Inruby,youcancreatecomplexobjectwithComplex,::rect,::polaror#to_cmethod.

Complex(1)#=>(1+0i)

Complex(2,3)#=>(2+3i)

Complex.polar(2,3)#=>(-1.9799849932008908+0.2822400161197344i)

3.to_c#=>(3+0i)

Youcanalsocreatecomplexobjectfromfloating-pointnumbersorstrings.

Complex(0.3)#=>(0.3+0i)

Complex('0.3-0.5i')#=>(0.3-0.5i)

Complex('2/3+3/4i')#=>((2/3)+(3/4)*i)

Complex('1@2')#=>(-0.4161468365471424+0.9092974268256817i)

0.3.to_c#=>(0.3+0i)

'0.3-0.5i'.to_c#=>(0.3-0.5i)

'2/3+3/4i'.to_c#=>((2/3)+(3/4)*i)

'1@2'.to_c#=>(-0.4161468365471424+0.9092974268256817i)

Acomplexobjectiseitheranexactoraninexactnumber.

Page 94: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Complex(1,1)/2#=>((1/2)+(1/2)*i)

Complex(1,1)/2.0#=>(0.5+0.5i)

InFilescomplex.c

ParentNumeric

Constants

I

Theimaginaryunit.

PublicClassMethods

Returnsacomplexobjectwhichdenotesthegivenpolarform.

Complex.polar(3,0)#=>(3.0+0.0i)

Complex.polar(3,Math::PI/2)#=>(1.836909530733566e-16+3.0i)

Complex.polar(3,Math::PI)#=>(-3.0+3.673819061467132e-16i)

Complex.polar(3,-Math::PI/2)#=>(1.836909530733566e-16-3.0i)

Returnsacomplexobjectwhichdenotesthegiven

polar(abs[,arg])→complex

rect(real[,imag])→complexrectangular(real[,imag])→complex

Page 95: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

rectangularform.

Complex.rectangular(1,2)#=>(1+2i)

Returnsacomplexobjectwhichdenotesthegivenrectangularform.

Complex.rectangular(1,2)#=>(1+2i)

PublicInstanceMethods

Performsmultiplication.

Complex(2,3)*Complex(2,3)#=>(-5+12i)

Complex(900)*Complex(1)#=>(900+0i)

Complex(-2,9)*Complex(-9,2)#=>(0-85i)

Complex(9,8)*4#=>(36+32i)

Complex(20,9)*9.8#=>(196.0+88.2i)

Performsexponentiation.

Complex('i')**2#=>(-1+0i)

Complex(-8)**Rational(1,3)#=>(1.0000000000000002+1.7320508075688772i)

Performsaddition.

Complex(2,3)+Complex(2,3)#=>(4+6i)

Complex(900)+Complex(1)#=>(901+0i)

rect(real[,imag])→complexrectangular(real[,imag])→complex

cmp*numeric→complex

cmp**numeric→complex

cmp+numeric→complex

Page 96: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Complex(-2,9)+Complex(-9,2)#=>(-11+11i)

Complex(9,8)+4#=>(13+8i)

Complex(20,9)+9.8#=>(29.8+9i)

Performssubtraction.

Complex(2,3)-Complex(2,3)#=>(0+0i)

Complex(900)-Complex(1)#=>(899+0i)

Complex(-2,9)-Complex(-9,2)#=>(7+7i)

Complex(9,8)-4#=>(5+8i)

Complex(20,9)-9.8#=>(10.2+9i)

Returnsnegationofthevalue.

-Complex(1,2)#=>(-1-2i)

Performsdivision.

Complex(2,3)/Complex(2,3)#=>((1/1)+(0/1)*i)

Complex(900)/Complex(1)#=>((900/1)+(0/1)*i)

Complex(-2,9)/Complex(-9,2)#=>((36/85)-(77/85)*i)

Complex(9,8)/4#=>((9/4)+(2/1)*i)

Complex(20,9)/9.8#=>(2.0408163265306123+0.9183673469387754i)

Returnstrueifcmpequalsobjectnumerically.

Complex(2,3)==Complex(2,3)#=>true

Complex(5)==5#=>true

Complex(0)==0.0#=>true

Complex('1/3')==0.33#=>false

Complex('1/2')=='1/2'#=>false

cmp-numeric→complex

-cmp→complex

cmp/numeric→complexquo(numeric)→complex

cmp==object→trueorfalse

Page 97: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheabsolutepartofitspolarform.

Complex(-1).abs#=>1

Complex(3.0,-4.0).abs#=>5.0

Returnssquareoftheabsolutevalue.

Complex(-1).abs2#=>1

Complex(3.0,-4.0).abs2#=>25.0

Returnstheanglepartofitspolarform.

Complex.polar(3,Math::PI/2).arg#=>1.5707963267948966

Returnstheanglepartofitspolarform.

Complex.polar(3,Math::PI/2).arg#=>1.5707963267948966

Returnsthecomplexconjugate.

abs→realmagnitude→real

abs2→real

arg→floatangle→floatphase→float

arg→floatangle→floatphase→float

conj→complexconjugate→complex

Page 98: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Complex(1,2).conjugate#=>(1-2i)

Returnsthecomplexconjugate.

Complex(1,2).conjugate#=>(1-2i)

Returnsthedenominator(lcmofbothdenominator-realandimag).

Seenumerator.

Performsdivisionaseachpartisafloat,neverreturnsafloat.

Complex(11,22).fdiv(3)#=>(3.6666666666666665+7.333333333333333i)

Returnstheimaginarypart.

Complex(7).imaginary#=>0

Complex(9,-4).imaginary#=>-4

Returnstheimaginarypart.

Complex(7).imaginary#=>0

Complex(9,-4).imaginary#=>-4

conj→complexconjugate→complex

denominator→integer

fdiv(numeric)→complex

imag→realimaginary→real

imag→realimaginary→real

Page 99: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthevalueasastringforinspection.

Complex(2).inspect#=>"(2+0i)"

Complex('-8/6').inspect#=>"((-4/3)+0i)"

Complex('1/2i').inspect#=>"(0+(1/2)*i)"

Complex(0,Float::INFINITY).inspect#=>"(0+Infinity*i)"

Complex(Float::NAN,Float::NAN).inspect#=>"(NaN+NaN*i)"

Returnstheabsolutepartofitspolarform.

Complex(-1).abs#=>1

Complex(3.0,-4.0).abs#=>5.0

Returnsthenumerator.

123+4i<-numerator

-+-i->----

236<-denominator

c=Complex('1/2+2/3i')#=>((1/2)+(2/3)*i)

n=c.numerator#=>(3+4i)

d=c.denominator#=>6

n/d#=>((1/2)+(2/3)*i)

Complex(Rational(n.real,d),Rational(n.imag,d))

#=>((1/2)+(2/3)*i)

Seedenominator.

inspect→string

abs→realmagnitude→real

numerator→numeric

arg→floatangle→float

Page 100: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheanglepartofitspolarform.

Complex.polar(3,Math::PI/2).arg#=>1.5707963267948966

Returnsanarray;[cmp.abs,cmp.arg].

Complex(1,2).polar#=>[2.23606797749979,1.1071487177940904]

Performsdivision.

Complex(2,3)/Complex(2,3)#=>((1/1)+(0/1)*i)

Complex(900)/Complex(1)#=>((900/1)+(0/1)*i)

Complex(-2,9)/Complex(-9,2)#=>((36/85)-(77/85)*i)

Complex(9,8)/4#=>((9/4)+(2/1)*i)

Complex(20,9)/9.8#=>(2.0408163265306123+0.9183673469387754i)

Returnsthevalueasarationalifpossible(theimaginarypartshouldbeexactlyzero).

Complex(1.0/3,0).rationalize#=>(1/3)

Complex(1,0.0).rationalize#RangeError

Complex(1,2).rationalize#RangeError

Seeto_r.

Returnstherealpart.

Complex(7).real#=>7

phase→float

polar→array

cmp/numeric→complexquo(numeric)→complex

rationalize([eps])→rational

real→real

Page 101: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Complex(9,-4).real#=>9

Returnsfalse.

Returnsanarray;[cmp.real,cmp.imag].

Complex(1,2).rectangular#=>[1,2]

Returnsanarray;[cmp.real,cmp.imag].

Complex(1,2).rectangular#=>[1,2]

Returnsself.

Complex(2).to_c#=>(2+0i)

Complex(-8,6).to_c#=>(-8+6i)

Returnsthevalueasafloatifpossible(theimaginarypartshouldbeexactlyzero).

Complex(1,0).to_f#=>1.0

Complex(1,0.0).to_f#RangeError

Complex(1,2).to_f#RangeError

real?→false

rect→arrayrectangular→array

rect→arrayrectangular→array

to_c→self

to_f→float

to_i→integer

Page 102: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthevalueasanintegerifpossible(theimaginarypartshouldbeexactlyzero).

Complex(1,0).to_i#=>1

Complex(1,0.0).to_i#RangeError

Complex(1,2).to_i#RangeError

Returnsthevalueasarationalifpossible(theimaginarypartshouldbeexactlyzero).

Complex(1,0).to_r#=>(1/1)

Complex(1,0.0).to_r#RangeError

Complex(1,2).to_r#RangeError

Seerationalize.

Returnsthevalueasastring.

Complex(2).to_s#=>"2+0i"

Complex('-8/6').to_s#=>"-4/3+0i"

Complex('1/2i').to_s#=>"0+1/2i"

Complex(0,Float::INFINITY).to_s#=>"0+Infinity*i"

Complex(Float::NAN,Float::NAN).to_s#=>"NaN+NaN*i"

Returnsthecomplexconjugate.

Complex(1,2).conjugate#=>(1-2i)

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

to_r→rational

to_s→string

conj→complexconjugate→complex

Page 103: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classComplex::compatible

InFilescomplex.c

ParentObject

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 104: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classContinuationContinuationobjectsaregeneratedbyKernel#callcc,afterhaving+require+dcontinuation.Theyholdareturnaddressandexecutioncontext,allowinganonlocalreturntotheendofthecallccblockfromanywherewithinaprogram.ContinuationsaresomewhatanalogoustoastructuredversionofC'ssetjmp/longjmp(althoughtheycontainmorestate,soyoumightconsiderthemclosertothreads).

Forinstance:

require"continuation"

arr=["Freddie","Herbie","Ron","Max","Ringo"

callcc{|cc|$cc=cc}

puts(message=arr.shift)

$cc.callunlessmessage=~/Max/

produces:

Freddie

Herbie

Ron

Max

This(somewhatcontrived)exampleallowstheinnerlooptoabandonprocessingearly:

Page 105: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

require"continuation"

callcc{|cont|

foriin0..4

print"\n#{i}:"

forjini*5...(i+1)*5

cont.call()ifj==17

printf"%3d",j

end

end

}

puts

produces:

0:01234

1:56789

2:1011121314

3:1516

InFilescont.c

ParentObject

PublicInstanceMethods

Invokesthecontinuation.Theprogramcontinuesfromtheendofthecallccblock.Ifnoargumentsaregiven,theoriginalcallccreturnsnil.Ifoneargument

call(args,...)cont[args,...]

Page 106: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

isgiven,callccreturnsit.Otherwise,anarraycontainingargsisreturned.

callcc{|cont|cont.call}#=>nil

callcc{|cont|cont.call1}#=>1

callcc{|cont|cont.call1,2,3}#=>[1,2,3]

Invokesthecontinuation.Theprogramcontinuesfromtheendofthecallccblock.Ifnoargumentsaregiven,theoriginalcallccreturnsnil.Ifoneargumentisgiven,callccreturnsit.Otherwise,anarraycontainingargsisreturned.

callcc{|cont|cont.call}#=>nil

callcc{|cont|cont.call1}#=>1

callcc{|cont|cont.call1,2,3}#=>[1,2,3]

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

call(args,...)cont[args,...]

Page 107: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classDataThisisarecommendedbaseclassforCextensionsusingData_Make_StructorData_Wrap_Struct,seeREADME.EXTfordetails.

InFilesobject.c

ParentObject

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 108: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classDirObjectsofclassDiraredirectorystreamsrepresentingdirectoriesintheunderlyingfilesystem.Theyprovideavarietyofwaystolistdirectoriesandtheircontents.SeealsoFile.

Thedirectoryusedintheseexamplescontainsthetworegularfiles(config.handmain.rb),theparentdirectory(..),andthedirectoryitself(.).

InFilesdir.c

ParentObject

IncludedModulesEnumerable

PublicClassMethods

EquivalenttocallingDir.glob([string,...],0).Dir[string[,string...]]→array

chdir([string])→0

Page 109: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Changesthecurrentworkingdirectoryoftheprocesstothegivenstring.Whencalledwithoutanargument,changesthedirectorytothevalueoftheenvironmentvariableHOME,orLOGDIR.SystemCallError(probablyErrno::ENOENT)ifthetargetdirectorydoesnotexist.

Ifablockisgiven,itispassedthenameofthenewcurrentdirectory,andtheblockisexecutedwiththatasthecurrentdirectory.Theoriginalworkingdirectoryisrestoredwhentheblockexits.Thereturnvalueofchdiristhevalueoftheblock.chdirblockscanbenested,butinamulti-threadedprogramanerrorwillberaisedifathreadattemptstoopenachdirblockwhileanotherthreadhasoneopen.

Dir.chdir("/var/spool/mail")

putsDir.pwd

Dir.chdir("/tmp")do

putsDir.pwd

Dir.chdir("/usr")do

putsDir.pwd

end

putsDir.pwd

end

putsDir.pwd

produces:

/var/spool/mail

/tmp

/usr

/tmp

/var/spool/mail

Changesthisprocess'sideaofthefilesystemroot.Onlyaprivilegedprocessmaymakethiscall.Notavailableonallplatforms.OnUnixsystems,see

chdir([string]){|path|block}→anObject

chroot(string)→0

Page 110: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

chroot(2)formoreinformation.

Deletesthenameddirectory.RaisesasubclassofSystemCallErrorifthedirectoryisn'tempty.

Returnsanarraycontainingallofthefilenamesinthegivendirectory.WillraiseaSystemCallErrorifthenameddirectorydoesn'texist.

Theoptionalencargumentspecifiestheencodingofthedirectory.Ifnotspecified,thefilesystemencodingisused.

Dir.entries("testdir")#=>[".","..","config.h","main.rb"]

Returnstrueifthenamedfileisadirectory,falseotherwise.

Deprecatedmethod.Don'tuse.

delete(string)→0rmdir(string)→0unlink(string)→0

entries(dirname)→arrayentries(dirname,encoding:enc)→array

exist?(file_name)→trueorfalse

exists?(file_name)→trueorfalse

foreach(dirname){|filename|block}→nilforeach(dirname,encoding:enc){|filename|block}→nilforeach(dirname)→an_enumerator

Page 111: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Callstheblockonceforeachentryinthenameddirectory,passingthefilenameofeachentryasaparametertotheblock.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

Dir.foreach("testdir"){|x|puts"Got#{x}"}

produces:

Got.

Got..

Gotconfig.h

Gotmain.rb

Returnsthepathtothecurrentworkingdirectoryofthisprocessasastring.

Dir.chdir("/tmp")#=>0

Dir.getwd#=>"/tmp"

Dir.pwd#=>"/tmp"

Expandspattern,whichisanArrayofpatternsorapatternString,andreturnstheresultsasmatchesorasargumentsgiventotheblock.

Notethatthispatternisnotaregexp,it'sclosertoashellglob.SeeFile.fnmatchforthemeaningoftheflagsparameter.Notethatcasesensitivitydepends

foreach(dirname,encoding:enc)→an_enumerator

getwd→stringpwd→string

glob(pattern,[flags])→matchesglob(pattern,[flags]){|filename|block}→nil

Page 112: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

onyoursystem(soFile::FNM_CASEFOLDisignored),asdoestheorderinwhichtheresultsarereturned.*

Matchesanyfile.Canberestrictedbyothervaluesintheglob.Equivalentto/.*/xinregexp.*

Matchesallfiles

c*

Matchesallfilesbeginningwithc

*c

Matchesallfilesendingwithc

*c*

Matchallfilesthathavecinthem(includingatthebeginningorend).

Note,thiswillnotmatchUnix-likehiddenfiles(dotfiles).Inordertoincludethoseinthematchresults,youmustusetheFile::FNM_DOTMATCHflagorsomethinglike"{*,.*}".

**

Matchesdirectoriesrecursively.

?

Matchesanyonecharacter.Equivalentto/.{1}/inregexp.

[set]

Matchesanyonecharacterinset.BehavesexactlylikecharactersetsinRegexp,includingsetnegation([^a-z]).

{p,q}

Matcheseitherliteralporliteralq.Equivalenttopatternalternationinregexp.

Matchingliteralsmaybemorethanonecharacter

Page 113: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

inlength.Morethantwoliteralsmaybespecified.

\

Escapesthenextmetacharacter.

Notethatthismeansyoucannotusebackslashonwindowsaspartofaglob,i.e.Dir["c:\foo*"]willnotwork,useDir["c:/foo*"]instead.

Examples:

Dir["config.?"]#=>["config.h"]

Dir.glob("config.?")#=>["config.h"]

Dir.glob("*.[a-z][a-z]")#=>["main.rb"]

Dir.glob("*.[^r]*")#=>["config.h"]

Dir.glob("*.{rb,h}")#=>["main.rb","config.h"]

Dir.glob("*")#=>["config.h","main.rb"]

Dir.glob("*",File::FNM_DOTMATCH)#=>[".","..","config.h","main.rb"]

rbfiles=File.join("**","*.rb")

Dir.glob(rbfiles)#=>["main.rb",

#"lib/song.rb",

#"lib/song/karaoke.rb"]

libdirs=File.join("**","lib")

Dir.glob(libdirs)#=>["lib"]

librbfiles=File.join("**","lib","**","*.rb")

Dir.glob(librbfiles)#=>["lib/song.rb",

#"lib/song/karaoke.rb"]

librbfiles=File.join("**","lib","*.rb")

Dir.glob(librbfiles)#=>["lib/song.rb"]

Returnsthehomedirectoryofthecurrentuserorthenameduserifgiven.

Makesanewdirectorynamedbystring,with

home()→"/home/me"home("root")→"/root"

mkdir(string[,integer])→0

Page 114: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

permissionsspecifiedbytheoptionalparameteranInteger.ThepermissionsmaybemodifiedbythevalueofFile::umask,andareignoredonNT.RaisesaSystemCallErrorifthedirectorycannotbecreated.SeealsothediscussionofpermissionsintheclassdocumentationforFile.

Dir.mkdir(File.join(Dir.home,".foo"),0700)#=>0

Returnsanewdirectoryobjectforthenameddirectory.

Theoptionalencargumentspecifiestheencodingofthedirectory.Ifnotspecified,thefilesystemencodingisused.

Theoptionalencargumentspecifiestheencodingofthedirectory.Ifnotspecified,thefilesystemencodingisused.

Withnoblock,openisasynonymforDir::new.Ifablockispresent,itispassedaDirasaparameter.Thedirectoryisclosedattheendoftheblock,andDir::openreturnsthevalueoftheblock.

new(string)→aDirnew(string,encoding:enc)→aDir

open(string)→aDiropen(string,encoding:enc)→aDiropen(string){|aDir|block}→anObjectopen(string,encoding:enc){|aDir|block}→anObject

getwd→string

Page 115: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthepathtothecurrentworkingdirectoryofthisprocessasastring.

Dir.chdir("/tmp")#=>0

Dir.getwd#=>"/tmp"

Dir.pwd#=>"/tmp"

Deletesthenameddirectory.RaisesasubclassofSystemCallErrorifthedirectoryisn'tempty.

Deletesthenameddirectory.RaisesasubclassofSystemCallErrorifthedirectoryisn'tempty.

PublicInstanceMethods

Closesthedirectorystream.AnyfurtherattemptstoaccessdirwillraiseanIOError.

d=Dir.new("testdir")

d.close#=>nil

Callstheblockonceforeachentryinthisdirectory,

pwd→string

delete(string)→0rmdir(string)→0unlink(string)→0

delete(string)→0rmdir(string)→0unlink(string)→0

close→nil

each{|filename|block}→direach→an_enumerator

Page 116: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

passingthefilenameofeachentryasaparametertotheblock.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

d=Dir.new("testdir")

d.each{|x|puts"Got#{x}"}

produces:

Got.

Got..

Gotconfig.h

Gotmain.rb

Returnsthefiledescriptorusedindir.

d=Dir.new("..")

d.fileno#=>8

Thismethodusesdirfd()functiondefinedbyPOSIX2008.NotImplementedErrorisraisedonotherplatforms,suchasWindows,whichdoesn'tprovidethefunction.

ReturnastringdescribingthisDirobject.

Returnsthepathparameterpassedtodir'sconstructor.

d=Dir.new("..")

d.path#=>".."

fileno→integer

inspect→string

path→stringornilto_path→stringornil

Page 117: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthecurrentpositionindir.SeealsoDir#seek.

d=Dir.new("testdir")

d.tell#=>0

d.read#=>"."

d.tell#=>12

SynonymforDir#seek,butreturnsthepositionparameter.

d=Dir.new("testdir")#=>#<Dir:0x401b3c40>

d.read#=>"."

i=d.pos#=>12

d.read#=>".."

d.pos=i#=>12

d.read#=>".."

Readsthenextentryfromdirandreturnsitasastring.Returnsnilattheendofthestream.

d=Dir.new("testdir")

d.read#=>"."

d.read#=>".."

d.read#=>"config.h"

Repositionsdirtothefirstentry.

d=Dir.new("testdir")

d.read#=>"."

d.rewind#=>#<Dir:0x401b3fb0>

d.read#=>"."

pos→integertell→integer

pos=integer→integer

read→stringornil

rewind→dir

Page 118: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Seekstoaparticularlocationindir.integermustbeavaluereturnedbyDir#tell.

d=Dir.new("testdir")#=>#<Dir:0x401b3c40>

d.read#=>"."

i=d.tell#=>12

d.read#=>".."

d.seek(i)#=>#<Dir:0x401b3c40>

d.read#=>".."

Returnsthecurrentpositionindir.SeealsoDir#seek.

d=Dir.new("testdir")

d.tell#=>0

d.read#=>"."

d.tell#=>12

Returnsthepathparameterpassedtodir'sconstructor.

d=Dir.new("..")

d.path#=>".."

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

seek(integer)→dir

pos→integertell→integer

path→stringornilto_path→stringornil

Page 119: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classENVENVisahash-likeaccessorforenvironmentvariables.

InFileshash.c

ParentObject

PublicClassMethods

RetrievesthevalueforenvironmentvariablenameasaString.Returnsnilifthenamedvariabledoesnotexist.

Setstheenvironmentvariablenametovalue.Ifthevaluegivenisniltheenvironmentvariableisdeleted.

ReturnsanArrayofthenameandvalueofthe

ENV[name]→value

ENV[name]=valuestore(name,value)→value

assoc(name)→Arrayornil

Page 120: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

environmentvariablewithnameornilifthenamecannotbefound.

Removeseveryenvironmentvariable.

Deletestheenvironmentvariablewithnameandreturnsthevalueofthevariable.Ifablockisgivenitwillbecalledwhenthenamedenvironmentdoesnotexist.

Deleteseveryenvironmentvariableforwhichtheblockevaluatestotrue.

Ifnoblockisgivenanenumeratorisreturnedinstead.

Yieldseachenvironmentvariablenameandvalue.

IfnoblockisgivenanEnumeratorisreturned.

Yieldseachenvironmentvariablename.

clear

delete(name)→valuedelete(name){|name|}→value

delete_if{|name,value|}→Hashdelete_if→Enumerator

each{|name,value|}→Hasheach→Enumeratoreach_pair{|name,value|}→Hasheach_pair→Enumerator

each_key{|name|}→Hasheach_key→Enumerator

Page 121: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

AnEnumeratorisreturnedifnoblockisgiven.

Yieldseachenvironmentvariablenameandvalue.

IfnoblockisgivenanEnumeratorisreturned.

Yieldseachenvironmentvariablevalue.

AnEnumeratorisreturnedifnoblockwasgiven.

Returnstruewhentherearenoenvironmentvariables

Retrievestheenvironmentvariablename.

IfthegivennamedoesnotexistandneitherdefaultnorablockaprovidedanIndexErrorisraised.Ifablockisgivenitiscalledwiththemissingnametoprovideavalue.Ifadefaultvalueisgivenitwillbereturnedwhennoblockisgiven.

each{|name,value|}→Hasheach→Enumeratoreach_pair{|name,value|}→Hasheach_pair→Enumerator

each_value{|value|}→Hasheach_value→Enumerator

empty?→trueorfalse

fetch(name)→valuefetch(name,default)→valuefetch(name){|missing_name|...}→value

key?(name)→trueorfalse

Page 122: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthereisanenvironmentvariablewiththegivenname.

Returnstrueifthereisanenvironmentvariablewiththegivenvalue.

Returnstrueifthereisanenvironmentvariablewiththegivenname.

Deprecatedmethodthatisequivalentto::key

ReturnsthecontentsoftheenvironmentasaString.

Returnsanewhashcreatedbyusingenvironmentvariablenamesasvaluesandvaluesasnames.

include?(name)→trueorfalsehas_key?(name)→trueorfalsemember?(name)→trueorfalse

value?(value)→trueorfalsehas_value?(value)→trueorfalse

key?(name)→trueorfalseinclude?(name)→trueorfalsehas_key?(name)→trueorfalsemember?(name)→trueorfalse

index(value)→key

inspect→string

invert→Hash

keep_if{|name,value|}→Hash

Page 123: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Deleteseveryenvironmentvariablewheretheblockevaluatestofalse.

Returnsanenumeratorifnoblockwasgiven.

Returnsthenameoftheenvironmentvariablewithvalue.Ifthevalueisnotfoundnilisreturned.

Returnstrueifthereisanenvironmentvariablewiththegivenname.

ReturnseveryenvironmentvariablenameinanArray

Returnsthenumberofenvironmentvariables.

Returnstrueifthereisanenvironmentvariablewiththegivenname.

keep_if→Enumerator

key(value)→name

key?(name)→trueorfalseinclude?(name)→trueorfalsehas_key?(name)→trueorfalsemember?(name)→trueorfalse

keys→Array

lengthsize

key?(name)→trueorfalseinclude?(name)→trueorfalsehas_key?(name)→trueorfalsemember?(name)→trueorfalse

Page 124: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsanArrayofthenameandvalueoftheenvironmentvariablewithvalueornilifthevaluecannotbefound.

Re-hashingtheenvironmentvariablesdoesnothing.ItisprovidedforcompatibilitywithHash.

SameasENV#delete_if,butworkson(andreturns)acopyoftheenvironment.

EquivalenttoENV#delete_ifbutreturnsnilifnochangesweremade.

ReturnsanEnumeratorifnoblockwasgiven.

Replacesthecontentsoftheenvironmentvariableswiththecontentsofhash.

Returnsacopyoftheenvironmentforentrieswheretheblockreturnstrue.

ReturnsanEnumeratorifnoblockwasgiven.

rassoc(value)

rehash

reject{|name,value|}→Hashreject→Enumerator

reject!{|name,value|}→ENVornilreject!→Enumerator

replace(hash)→env

select{|name,value|}→Hashselect→Enumerator

Page 125: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

EquivalenttoENV#keep_ifbutreturnsnilifnochangesweremade.

Removesanenvironmentvariablename-valuepairfromENVandreturnsitasanArray.Returnsnilifwhentheenvironmentisempty.

Returnsthenumberofenvironmentvariables.

Setstheenvironmentvariablenametovalue.Ifthevaluegivenisniltheenvironmentvariableisdeleted.

Convertstheenvironmentvariablesintoanarrayofnamesandvaluearrays.

ENV.to_a#=>[["TERM","xterm-color"],["SHELL","/bin/bash"],...]

Createsahashwithacopyoftheenvironmentvariables.

select!{|name,value|}→ENVornilselect!→Enumerator

shift→Arrayornil

lengthsize

ENV[name]=valuestore(name,value)→value

to_a→Array

to_hash→hashto_h→hash

Page 126: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Createsahashwithacopyoftheenvironmentvariables.

Returns“ENV”

Addsthecontentsofhashtotheenvironmentvariables.Ifnoblockisspecifiedentrieswithduplicatekeysareoverwritten,otherwisethevalueofeachduplicatenameisdeterminedbycallingtheblockwiththekey,itsvaluefromtheenvironmentanditsvaluefromthehash.

Returnstrueifthereisanenvironmentvariablewiththegivenvalue.

ReturnseveryenvironmentvariablevalueasanArray

Returnsanarraycontainingtheenvironmentvariablevaluesassociatedwiththegivennames.Seealso::select.

to_hash→hashto_h→hash

to_s→"ENV"

update(hash)→Hashupdate(hash){|name,old_value,new_value|}→Hash

value?(value)→trueorfalsehas_value?(value)→trueorfalse

values→Array

values_at(name,...)→Array

Page 127: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 128: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEOFErrorRaisedbysomeIOoperationswhenreachingtheendoffile.ManyIOmethodsexistintwoforms,

onethatreturnsnilwhentheendoffileisreached,theotherraisesEOFErrorEOFError.

EOFErrorisasubclassofIOError.

file=File.open("/etc/hosts")

file.read

file.gets#=>nil

file.readline#=>EOFError:endoffilereached

InFilesio.c

ParentIOError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 129: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEncodingAnEncodinginstancerepresentsacharacterencodingusableinRuby.ItisdefinedasaconstantundertheEncodingnamespace.Ithasanameandoptionally,aliases:

Encoding::ISO_8859_1.name

#=>#<Encoding:ISO-8859-1>

Encoding::ISO_8859_1.names

#=>["ISO-8859-1","ISO8859-1"]

RubymethodsdealingwithencodingsreturnoracceptEncodinginstancesasarguments(whenamethodacceptsanEncodinginstanceasanargument,itcanbepassedanEncodingnameoraliasinstead).

"somestring".encoding

#=>#<Encoding:UTF-8>

string="somestring".encode(Encoding::ISO_8859_1

#=>"somestring"

string.encoding

#=>#<Encoding:ISO-8859-1>

"somestring".encode"ISO-8859-1"

#=>"somestring"

Encoding::ASCII_8BITisaspecialencodingthatisusuallyusedforabytestring,notacharacter

Page 130: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

string.Butasthenameinsists,itscharactersintherangeofASCIIareconsideredasASCIIcharacters.ThisisusefulwhenyouuseASCII-8BITcharacterswithotherASCIIcompatiblecharacters.

Page 131: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Changinganencoding

TheassociatedEncodingofaStringcanbechangedintwodifferentways.

First,itispossibletosettheEncodingofastringtoanewEncodingwithoutchangingtheinternalbyterepresentationofthestring,withString#force_encoding.ThisishowyoucantellRubythecorrectencodingofastring.

string

#=>"R\xC3\xA9sum\xC3\xA9"

string.encoding

#=>#<Encoding:ISO-8859-1>

string.force_encoding(Encoding::UTF_8)

#=>"R\u00E9sum\u00E9"

Second,itispossibletotranscodeastring,i.e.translateitsinternalbyterepresentationtoanotherencoding.Itsassociatedencodingisalsosettotheotherencoding.SeeString#encodeforthevariousformsoftranscoding,andtheEncoding::Converterclassforadditionalcontroloverthetranscodingprocess.

string

#=>"R\u00E9sum\u00E9"

string.encoding

#=>#<Encoding:UTF-8>

string=string.encode!(Encoding::ISO_8859_1)

#=>"R\xE9sum\xE9"

string.encoding

Page 132: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#=>#<Encoding::ISO-8859-1>

Page 133: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Scriptencoding

AllRubyscriptcodehasanassociatedEncodingwhichanyStringliteralcreatedinthesourcecodewillbeassociatedto.

ThedefaultscriptencodingisEncoding::UTF-8afterv2.0,butitcanbechangedbyamagiccommentonthefirstlineofthesourcecodefile(orsecondline,ifthereisashebanglineonthefirst).Thecommentmustcontainthewordcodingorencoding,followedbyacolon,spaceandtheEncodingnameoralias:

#encoding:UTF-8

"somestring".encoding

#=>#<Encoding:UTF-8>

The__ENCODING__keywordreturnsthescriptencodingofthefilewhichthekeywordiswritten:

#encoding:ISO-8859-1

__ENCODING__

#=>#<Encoding:ISO-8859-1>

ruby-Kwillchangethedefaultlocaleencoding,butthisisnotrecommended.RubysourcefilesshoulddeclareitsscriptencodingbyamagiccommentevenwhentheyonlydependonUS-ASCIIstringsorregularexpressions.

Page 134: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Localeencoding

Thedefaultencodingoftheenvironment.Usuallyderivedfromlocale.

seeEncoding.locale_charmap,::find('locale')

Page 135: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Filesystemencoding

Thedefaultencodingofstringsfromthefilesystemoftheenvironment.Thisisusedforstringsoffilenamesorpaths.

see::find('filesystem')

Page 136: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Externalencoding

EachIOobjecthasanexternalencodingwhichindicatestheencodingthatRubywillusetoreaditsdata.BydefaultRubysetstheexternalencodingofanIOobjecttothedefaultexternalencoding.Thedefaultexternalencodingissetbylocaleencodingortheinterpreter-Eoption.::default_externalreturnsthecurrentvalueoftheexternalencoding.

ENV["LANG"]

#=>"UTF-8"

Encoding.default_external

#=>#<Encoding:UTF-8>

$ruby-EISO-8859-1-e"pEncoding.default_external"

#<Encoding:ISO-8859-1>

$LANG=Cruby-e'pEncoding.default_external'

#<Encoding:US-ASCII>

Thedefaultexternalencodingmayalsobesetthrough::default_external=,butyoushouldnotdothisasstringscreatedbeforeandafterthechangewillhaveinconsistentencodings.Insteaduseruby-Etoinvokerubywiththecorrectexternalencoding.

WhenyouknowthattheactualencodingofthedataofanIOobjectisnotthedefaultexternalencoding,youcanresetitsexternalencodingwithIO#set_encodingorsetitatIOobject

Page 137: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

creation(seeIO.newoptions).

Page 138: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Internalencoding

ToprocessthedataofanIOobjectwhichhasanencodingdifferentfromitsexternalencoding,youcansetitsinternalencoding.RubywillusethisinternalencodingtotranscodethedatawhenitisreadfromtheIOobject.

Conversely,whendataiswrittentotheIOobjectitistranscodedfromtheinternalencodingtotheexternalencodingoftheIOobject.

TheinternalencodingofanIOobjectcanbesetwithIO#set_encodingoratIOobjectcreation(seeIO.newoptions).

Theinternalencodingisoptionalandwhennotset,theRubydefaultinternalencodingisused.Ifnotexplicitlysetthisdefaultinternalencodingisnilmeaningthatbydefault,notranscodingoccurs.

Thedefaultinternalencodingcanbesetwiththeinterpreteroption-E.::default_internalreturnsthecurrentinternalencoding.

$ruby-e'pEncoding.default_internal'

nil

$ruby-EISO-8859-1:UTF-8-e"p[Encoding.default_external,\

Encoding.default_internal]"

[#<Encoding:ISO-8859-1>,#<Encoding:UTF-8>]

Page 139: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thedefaultinternalencodingmayalsobesetthrough::default_internal=,butyoushouldnotdothisasstringscreatedbeforeandafterthechangewillhaveinconsistentencodings.Insteaduseruby-Etoinvokerubywiththecorrectinternalencoding.

Page 140: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

IOencodingexample

InthefollowingexampleaUTF-8encodedstring“Ru00E9sumu00E9”istranscodedforoutputtoISO-8859-1encoding,thenreadbackinandtranscodedtoUTF-8:

string="R\u00E9sum\u00E9"

open("transcoded.txt","w:ISO-8859-1")do|io|

io.write(string)

end

puts"rawtext:"

pFile.binread("transcoded.txt")

puts

open("transcoded.txt","r:ISO-8859-1:UTF-8")do|

puts"transcodedtext:"

pio.read

end

Whilewritingthefile,theinternalencodingisnotspecifiedasitisonlynecessaryforreading.Whilereadingthefileboththeinternalandexternalencodingmustbespecifiedtoobtainthecorrectresult.

$rubyt.rb

rawtext:

"R\xE9sum\xE9"

transcodedtext:

"R\u00E9sum\u00E9"

Page 141: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

InFilesencoding.ctranscode.c

ParentObject

PublicClassMethods

Returnsthehashofavailableencodingaliasandoriginalencodingname.

Encoding.aliases

#=>{"BINARY"=>"ASCII-8BIT","ASCII"=>"US-ASCII","ANSI_X3.4-1986"=>"US-ASCII",

"SJIS"=>"Shift_JIS","eucJP"=>"EUC-JP","CP932"=

Checksthecompatibilityoftwoobjects.

Iftheobjectsarebothstringstheyarecompatiblewhentheyareconcatenatable.Theencodingoftheconcatenatedstringwillbereturnediftheyarecompatible,niliftheyarenot.

Encoding.compatible?("\xa1".force_encoding("iso-8859-1"

#=>#<Encoding:ISO-8859-1>

Encoding.compatible?(

"\xa1".force_encoding("iso-8859-1"),

"\xa1\xa1".force_encoding("euc-jp"))

#=>nil

aliases->{"alias1"=>"orig1","alias2"→"orig2",...}

compatible?(obj1,obj2)→encornil

Page 142: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Iftheobjectsarenon-stringstheirencodingsarecompatiblewhentheyhaveanencodingand:

EitherencodingisUS-ASCIIcompatible

Oneoftheencodingsisa7-bitencoding

Returnsdefaultexternalencoding.

Thedefaultexternalencodingisusedbydefaultforstringscreatedfromthefollowinglocations:

CSV

Filedatareadfromdisk

SDBM

StringIO

Zlib::GzipReader

Zlib::GzipWriter

String#inspect

Regexp#inspect

Whilestringscreatedfromtheselocationswillhavethisencoding,theencodingmaynotbevalid.BesuretocheckString#valid_encoding?.

Filedatawrittentodiskwillbetranscodedtothedefaultexternalencodingwhenwritten.

Thedefaultexternalencodingisinitializedbythelocaleor-Eoption.

Setsdefaultexternalencoding.Youshouldnotset::default_externalinrubycodeasstringscreatedbeforechangingthevaluemayhaveadifferent

default_external→enc

default_external=enc

Page 143: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

encodingfromstringscreatedafterthevaluewaschanged.,insteadyoushoulduseruby-Etoinvokerubywiththecorrectdefault_external.

See::default_externalforinformationonhowthedefaultexternalencodingisused.

Returnsdefaultinternalencoding.Stringswillbetranscodedtothedefaultinternalencodinginthefollowingplacesifthedefaultinternalencodingisnotnil:

CSV

Etc.sysconfdirandEtc.systmpdir

Filedatareadfromdisk

FilenamesfromDir

Integer#chr

String#inspectandRegexp#inspect

StringsreturnedfromReadline

StringsreturnedfromSDBM

Time#zone

ValuesfromENV

ValuesinARGVincluding$PROGRAM_NAME

AdditionallyString#encodeandString#encode!usethedefaultinternalencodingifnoencodingisgiven.

Thelocaleencoding(__ENCODING__),not::default_internal,isusedastheencodingofcreatedstrings.

::default_internalisinitializedbythesourcefile'sinternal_encodingor-Eoption.

default_internal→enc

Page 144: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Setsdefaultinternalencodingorremovesdefaultinternalencodingwhenpassednil.Youshouldnotset::default_internalinrubycodeasstringscreatedbeforechangingthevaluemayhaveadifferentencodingfromstringscreatedafterthechange.Insteadyoushoulduseruby-Etoinvokerubywiththecorrectdefault_internal.

See::default_internalforinformationonhowthedefaultinternalencodingisused.

Searchtheencodingwithspecifiedname.nameshouldbeastring.

Encoding.find("US-ASCII")#=>#<Encoding:US-ASCII>

Nameswhichthismethodacceptareencodingnamesandaliasesincludingfollowingspecialaliases

“external”defaultexternalencoding

“internal”defaultinternalencoding

“locale”localeencoding

“filesystem”filesystemencoding

AnArgumentErrorisraisedwhennoencodingwithname.OnlyEncoding.find("internal")howeverreturnsnilwhennoencodingnamed“internal”,inotherwords,whenRubyhasnodefaultinternalencoding.

default_internal=encornil

find(string)→enc

Page 145: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthelistofloadedencodings.

Encoding.list

#=>[#<Encoding:ASCII-8BIT>,#<Encoding:UTF-8>,

#<Encoding:ISO-2022-JP(dummy)>]

Encoding.find("US-ASCII")

#=>#<Encoding:US-ASCII>

Encoding.list

#=>[#<Encoding:ASCII-8BIT>,#<Encoding:UTF-8>,

#<Encoding:US-ASCII>,#<Encoding:ISO-2022-JP(dummy)>]

Returnsthelistofavailableencodingnames.

Encoding.name_list

#=>["US-ASCII","ASCII-8BIT","UTF-8",

"ISO-8859-1","Shift_JIS","EUC-JP",

"Windows-31J",

"BINARY","CP932","eucJP"]

PublicInstanceMethods

ReturnswhetherASCII-compatibleornot.

Encoding::UTF_8.ascii_compatible?#=>true

Encoding::UTF_16BE.ascii_compatible?#=>false

Returnstruefordummyencodings.Adummyencodingisanencodingforwhichcharacterhandlingisnotproperlyimplemented.Itisusedforstateful

list→[enc1,enc2,...]

name_list→["enc1","enc2",...]

ascii_compatible?→trueorfalse

dummy?→trueorfalse

Page 146: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

encodings.

Encoding::ISO_2022_JP.dummy?#=>true

Encoding::UTF_8.dummy?#=>false

Returnsastringwhichrepresentstheencodingforprogrammers.

Encoding::UTF_8.inspect#=>"#<Encoding:UTF-8>"

Encoding::ISO_2022_JP.inspect#=>"#<Encoding:ISO-2022-JP(dummy)>"

Returnsthenameoftheencoding.

Encoding::UTF_8.name#=>"UTF-8"

Returnsthelistofnameandaliasesoftheencoding.

Encoding::WINDOWS_31J.names#=>["Windows-31J","CP932","csWindows31J"]

Returnsareplicatedencodingofencwhosenameisname.Thenewencodingshouldhavethesamebytestructureofenc.Ifnameisusedbyanotherencoding,raiseArgumentError.

Returnsthenameoftheencoding.

inspect→string

name→stringto_s→string

names→array

replicate(name)→encoding

name→stringto_s→string

Page 147: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Encoding::UTF_8.name#=>"UTF-8"

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 148: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEncoding::CompatibilityErrorRaisedbyEncodingandStringmethodswhenthesourceencodingisincompatiblewiththetargetencoding.

InFilesencoding.c

ParentEncodingError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 149: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEncoding::Converter

InFilesencoding.c

ParentData

Constants

AFTER_OUTPUT

AFTER_OUTPUT

Stopconvertingaftersomeoutputiscompletebutbeforealloftheinputwasconsumed.See#primitive_convertforanexample.

CRLF_NEWLINE_DECORATOR

CRLF_NEWLINE_DECORATOR

DecoratorforconvertingLFtoCRLF

CR_NEWLINE_DECORATOR

CR_NEWLINE_DECORATOR

DecoratorforconvertingLFtoCR

INVALID_MASK

Page 150: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

INVALID_MASK

Maskforinvalidbytesequences

INVALID_REPLACE

INVALID_REPLACE

Replaceinvalidbytesequences

PARTIAL_INPUT

PARTIAL_INPUT

Indicatesthesourcemaybepartofalargerstring.See#primitive_convertforanexample.

UNDEF_HEX_CHARREF

UNDEF_HEX_CHARREF

ReplacebytesequencesthatareundefinedinthedestinationencodingwithanXMLhexadecimalcharacterreference.ThisisvalidforXMLconversion.

UNDEF_MASK

UNDEF_MASK

Maskforavalidcharacterinthesourceencodingbutnorelatedcharacter(s)indestinationencoding.

UNDEF_REPLACE

UNDEF_REPLACE

Replacebytesequencesthatareundefinedinthedestinationencoding.

UNIVERSAL_NEWLINE_DECORATOR

Page 151: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

UNIVERSAL_NEWLINE_DECORATOR

DecoratorforconvertingCRLFandCRtoLF

XML_ATTR_CONTENT_DECORATOR

XML_ATTR_CONTENT_DECORATOR

EscapeasXMLAttValue

XML_ATTR_QUOTE_DECORATOR

XML_ATTR_QUOTE_DECORATOR

EscapeasXMLAttValue

XML_TEXT_DECORATOR

XML_TEXT_DECORATOR

EscapeasXMLCharData

PublicClassMethods

ReturnsthecorrespondingASCIIcompatibleencoding.

ReturnsniliftheargumentisanASCIIcompatibleencoding.

“correspondingASCIIcompatibleencoding”isanASCIIcompatibleencodingwhichcanrepresentsexactlythesamecharactersasthegivenASCIIincompatibleencoding.So,noconversionundefined

Encoding::Converter.asciicompat_encoding(string)→encodingornilEncoding::Converter.asciicompat_encoding(encoding)→encodingornil

Page 152: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

erroroccurswhenconvertingbetweenthetwoencodings.

Encoding::Converter.asciicompat_encoding("ISO-2022-JP"

Encoding::Converter.asciicompat_encoding("UTF-16BE")#=>#<Encoding:UTF-8>

Encoding::Converter.asciicompat_encoding("UTF-8")#=>nil

possibleoptionselements:

hashform:

:invalid=>nil#raiseerroroninvalidbytesequence(default)

:invalid=>:replace#replaceinvalidbytesequence

:undef=>nil#raiseerroronundefinedconversion(default)

:undef=>:replace#replaceundefinedconversion

:replace=>string#replacementstring("?"or"\uFFFD"ifnotspecified)

:newline=>:universal#decoratorforconvertingCRLFandCRtoLF

:newline=>:crlf#decoratorforconvertingLFtoCRLF

:newline=>:cr#decoratorforconvertingLFtoCR

:universal_newline=>true#decoratorforconvertingCRLFandCRtoLF

:crlf_newline=>true#decoratorforconvertingLFtoCRLF

:cr_newline=>true#decoratorforconvertingLFtoCR

:xml=>:text#escapeasXMLCharData.

:xml=>:attr#escapeasXMLAttValue

integerform:

Encoding::Converter::INVALID_REPLACE

Encoding::Converter::UNDEF_REPLACE

Encoding::Converter::UNDEF_HEX_CHARREF

Encoding::Converter::UNIVERSAL_NEWLINE_DECORATOR

Encoding::Converter::CRLF_NEWLINE_DECORATOR

Encoding::Converter::CR_NEWLINE_DECORATOR

Encoding::Converter::XML_TEXT_DECORATOR

Encoding::Converter::XML_ATTR_CONTENT_DECORATOR

Encoding::Converter::XML_ATTR_QUOTE_DECORATOR

::newcreatesaninstanceofEncoding::Converter.

Encoding::Converter.new(source_encoding,destination_encoding)Encoding::Converter.new(source_encoding,destination_encoding,opt)Encoding::Converter.new(convpath)

Page 153: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Source_encodingand#destination_encodingshouldbeastringorEncodingobject.

optshouldbenil,ahashoraninteger.

convpathshouldbeanarray.convpathmaycontain

two-elementarrayswhichcontainencodingsorencodingnames,or

stringsrepresentingdecoratornames.

::newoptionallytakesanoption.Theoptionshouldbeahashoraninteger.Theoptionhashcancontain:invalid=>nil,etc.Theoptionintegershouldbelogical-orofconstantssuchasEncoding::Converter::INVALID_REPLACE,etc.

:invalid=>nilRaiseerroroninvalidbytesequence.Thisisadefaultbehavior.

:invalid=>:replaceReplaceinvalidbytesequencebyreplacementstring.

:undef=>nilRaiseanerrorifacharacterin#source_encodingisnotdefinedindestination_encoding.Thisisadefaultbehavior.

:undef=>:replaceReplaceundefinedcharacterin#destination_encodingwithreplacementstring.

:replace=>stringSpecifythereplacementstring.Ifnot

Page 154: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

specified,“uFFFD”isusedforUnicodeencodingsand“?”forothers.

:universal_newline=>trueConvertCRLFandCRtoLF.

:crlf_newline=>trueConvertLFtoCRLF.

:cr_newline=>trueConvertLFtoCR.

:xml=>:textEscapeasXMLCharData.ThisformcanbeusedasaHTML4.0#PCDATA.

'&'->'&amp;'

'<'->'&lt;'

'>'->'&gt;'

undefinedcharactersin#destination_encoding->hexadecimalCharRefsuchas&xHH;

:xml=>:attrEscapeasXMLAttValue.Theconvertedresultisquotedas“…”.ThisformcanbeusedasaHTML4.0attributevalue.

'&'->'&amp;'

'<'->'&lt;'

'>'->'&gt;'

'“'->'&quot;'

undefinedcharactersin#destination_encoding->

Page 155: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

hexadecimalCharRefsuchas&xHH;

Examples:

#UTF-16BEtoUTF-8

ec=Encoding::Converter.new("UTF-16BE","UTF-8")

#Usually,decoratorssuchasnewlineconversionareinsertedlast.

ec=Encoding::Converter.new("UTF-16BE","UTF-8",:universal_newline

pec.convpath#=>[[#<Encoding:UTF-16BE>,#<Encoding:UTF-8>],

#"universal_newline"]

#But,ifthelastencodingisASCIIincompatible,

#decoratorsareinsertedbeforethelastconversion.

ec=Encoding::Converter.new("UTF-8","UTF-16BE",:crlf_newline

pec.convpath#=>["crlf_newline",

#[#<Encoding:UTF-8>,#<Encoding:UTF-16BE>]]

#Conversionpathcanbespecifieddirectly.

ec=Encoding::Converter.new(["universal_newline",["EUC-JP"

pec.convpath#=>["universal_newline",

#[#<Encoding:EUC-JP>,#<Encoding:UTF-8>],

#[#<Encoding:UTF-8>,#<Encoding:UTF-16BE>]]

Returnsaconversionpath.

pEncoding::Converter.search_convpath("ISO-8859-1","EUC-JP"

#=>[[#<Encoding:ISO-8859-1>,#<Encoding:UTF-8>],

#[#<Encoding:UTF-8>,#<Encoding:EUC-JP>]]

pEncoding::Converter.search_convpath("ISO-8859-1","EUC-JP"

or

pEncoding::Converter.search_convpath("ISO-8859-1","EUC-JP"

#=>[[#<Encoding:ISO-8859-1>,#<Encoding:UTF-8>],

#[#<Encoding:UTF-8>,#<Encoding:EUC-JP>],

#"universal_newline"]

pEncoding::Converter.search_convpath("ISO-8859-1","UTF-32BE"

Encoding::Converter.search_convpath(source_encoding,destination_encoding)→aryEncoding::Converter.search_convpath(source_encoding,destination_encoding,opt)→ary

Page 156: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

or

pEncoding::Converter.search_convpath("ISO-8859-1","UTF-32BE"

#=>[[#<Encoding:ISO-8859-1>,#<Encoding:UTF-8>],

#"universal_newline",

#[#<Encoding:UTF-8>,#<Encoding:UTF-32BE>]]

PublicInstanceMethods

Convertsource_stringandreturndestination_string.

source_stringisassumedasapartofsource.i.e.:partial_input=>trueisspecifiedinternally.finishmethodshouldbeusedlast.

ec=Encoding::Converter.new("utf-8","euc-jp")

putsec.convert("\u3042").dump#=>"\xA4\xA2"

putsec.finish.dump#=>""

ec=Encoding::Converter.new("euc-jp","utf-8")

putsec.convert("\xA4").dump#=>""

putsec.convert("\xA2").dump#=>"\xE3\x81\x82"

putsec.finish.dump#=>""

ec=Encoding::Converter.new("utf-8","iso-2022-jp")

putsec.convert("\xE3").dump#=>"".force_encoding("ISO-2022-JP")

putsec.convert("\x81").dump#=>"".force_encoding("ISO-2022-JP")

putsec.convert("\x82").dump#=>"\e$B$\"".force_encoding("ISO-2022-JP")

putsec.finish.dump#=>"\e(B".force_encoding("ISO-2022-JP")

Ifaconversionerroroccur,Encoding::UndefinedConversionErrororEncoding::InvalidByteSequenceErrorisraised.#convertdoesn'tsupplymethodstorecoverorrestartfromtheseexceptions.Whenyouwanttohandletheseconversionerrors,use#primitive_convert.

ec==other→trueorfalse

convert(source_string)→destination_string

Page 157: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheconversionpathofec.

Theresultisanarrayofconversions.

ec=Encoding::Converter.new("ISO-8859-1","EUC-JP",crlf_newline

pec.convpath

#=>[[#<Encoding:ISO-8859-1>,#<Encoding:UTF-8>],

#[#<Encoding:UTF-8>,#<Encoding:EUC-JP>],

#"crlf_newline"]

Eachelementofthearrayisapairofencodingsorastring.Apairmeansanencodingconversion.Astringmeansadecorator.

Intheaboveexample,[#<Encoding:ISO-8859-1>,#<Encoding:UTF-8>]meansaconverterfromISO-8859-1toUTF-8.“crlf_newline”meansnewlineconverterfromLFtoCRLF.

ReturnsthedestinationencodingasanEncodingobject.

Finishestheconverter.Itreturnsthelastpartoftheconvertedstring.

ec=Encoding::Converter.new("utf-8","iso-2022-jp")

pec.convert("\u3042")#=>"\e$B$\""

pec.finish#=>"\e(B"

Insertsstringintotheencodingconverter.Thestringwillbeconvertedtothedestinationencodingand

convpath→ary

destination_encoding→encoding

finish→string

insert_output(string)→nil

Page 158: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

outputonlaterconversions.

Ifthedestinationencodingisstateful,stringisconvertedaccordingtothestateandthestateisupdated.

Thismethodshouldbeusedonlywhenaconversionerroroccurs.

ec=Encoding::Converter.new("utf-8","iso-8859-1")

src="HIRAGANALETTERAis\u{3042}."

dst=""

pec.primitive_convert(src,dst)#=>:undefined_conversion

puts"[#{dst.dump},#{src.dump}]"#=>["HIRAGANALETTERAis","."]

ec.insert_output("<err>")

pec.primitive_convert(src,dst)#=>:finished

puts"[#{dst.dump},#{src.dump}]"#=>["HIRAGANALETTERAis<err>.",""]

ec=Encoding::Converter.new("utf-8","iso-2022-jp")

src="\u{306F3041306826613002}"#U+2661isnotrepresentableiniso-2022-jp

dst=""

pec.primitive_convert(src,dst)#=>:undefined_conversion

puts"[#{dst.dump},#{src.dump}]"#=>["\e$B$O$!$H".force_encoding("ISO-2022-JP"),"\xE3\x80\x82"]

ec.insert_output"?"#statechangerequiredtooutput"?".

pec.primitive_convert(src,dst)#=>:finished

puts"[#{dst.dump},#{src.dump}]"#=>["\e$B$O$!$H\e(B?\e$B!#\e(B".force_encoding("ISO-2022-JP"),""]

Returnsaprintableversionofec

ec=Encoding::Converter.new("iso-8859-1","utf-8")

putsec.inspect#=>#<Encoding::Converter:ISO-8859-1toUTF-8>

Returnsanexceptionobjectforthelastconversion.Returnsnilifthelastconversiondidnotproduceanerror.

“error”meansthat

inspect→string

last_error→exceptionornil

Page 159: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Encoding::InvalidByteSequenceErrorandEncoding::UndefinedConversionErrorfor#convertand:invalid_byte_sequence,:incomplete_inputand:undefined_conversionfor#primitive_convert.

ec=Encoding::Converter.new("utf-8","iso-8859-1")

pec.primitive_convert(src="\xf1abcd",dst="")#=>:invalid_byte_sequence

pec.last_error#=>#<Encoding::InvalidByteSequenceError:"\xF1"followedby"a"onUTF-8>

pec.primitive_convert(src,dst,nil,1)#=>:destination_buffer_full

pec.last_error#=>nil

possibleoptelements:

hashform:

:partial_input=>true#sourcebuffermaybepartoflargersource

:after_output=>true#stopconversionafteroutputbeforeinput

integerform:

Encoding::Converter::PARTIAL_INPUT

Encoding::Converter::AFTER_OUTPUT

possibleresults:

:invalid_byte_sequence

:incomplete_input

:undefined_conversion

:after_output

primitive_convert(source_buffer,destination_buffer)→symbolprimitive_convert(source_buffer,destination_buffer,destination_byteoffset)→symbolprimitive_convert(source_buffer,destination_buffer,destination_byteoffset,destination_bytesize)→symbolprimitive_convert(source_buffer,destination_buffer,destination_byteoffset,destination_bytesize,opt)→symbol

Page 160: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

:destination_buffer_full

:source_buffer_empty

:finished

#primitive_convertconvertssource_bufferintodestination_buffer.

source_buffershouldbeastringornil.nilmeansanemptystring.

destination_buffershouldbeastring.

destination_byteoffsetshouldbeanintegerornil.nilmeanstheendofdestination_buffer.Ifitisomitted,nilisassumed.

destination_bytesizeshouldbeanintegerornil.nilmeansunlimited.Ifitisomitted,nilisassumed.

optshouldbenil,ahashoraninteger.nilmeansnoflags.Ifitisomitted,nilisassumed.

#primitive_convertconvertsthecontentofsource_bufferfrombeginningandstoretheresultintodestination_buffer.

destination_byteoffsetanddestination_bytesizespecifytheregionwhichtheconvertedresultisstored.destination_byteoffsetspecifiesthestartpositionindestination_bufferinbytes.Ifdestination_byteoffsetisnil,destination_buffer.bytesizeisusedforappendingtheresult.destination_bytesizespecifiesmaximumnumberofbytes.Ifdestination_bytesizeisnil,destinationsizeisunlimited.Afterconversion,destination_bufferisresizedtodestination_byteoffset+actuallyproducednumberofbytes.Alsodestination_buffer'sencodingissettodestination_encoding.

#primitive_convertdropstheconvertedpartofsource_buffer.thedroppedpartisconvertedindestination_bufferorbufferedinEncoding::Converter

Page 161: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

object.

#primitive_convertstopsconversionwhenoneoffollowingconditionmet.

invalidbytesequencefoundinsourcebuffer(:invalid_byte_sequence)primitive_errinfoandlast_errormethodsreturnsthedetailoftheerror.

unexpectedendofsourcebuffer(:incomplete_input)thisoccuronlywhen:partial_inputisnotspecified.primitive_errinfoandlast_errormethodsreturnsthedetailoftheerror.

characternotrepresentableinoutputencoding(:undefined_conversion)primitive_errinfoandlast_errormethodsreturnsthedetailoftheerror.

aftersomeoutputisgenerated,beforeinputisdone(:after_output)thisoccuronlywhen:after_outputisspecified.

destinationbufferisfull(:destination_buffer_full)thisoccuronlywhendestination_bytesizeisnon-nil.

sourcebufferisempty(:source_buffer_empty)thisoccuronlywhen:partial_inputisspecified.

conversionisfinished(:finished)

example:

ec=Encoding::Converter.new("UTF-8","UTF-16BE")

ret=ec.primitive_convert(src="pi",dst="",nil,100)

p[ret,src,dst]#=>[:finished,"","\x00p\x00i"]

ec=Encoding::Converter.new("UTF-8","UTF-16BE")

ret=ec.primitive_convert(src="pi",dst="",nil,1)

p[ret,src,dst]#=>[:destination_buffer_full,"i","\x00"]

ret=ec.primitive_convert(src,dst="",nil,1)

Page 162: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

p[ret,src,dst]#=>[:destination_buffer_full,"","p"]

ret=ec.primitive_convert(src,dst="",nil,1)

p[ret,src,dst]#=>[:destination_buffer_full,"","\x00"]

ret=ec.primitive_convert(src,dst="",nil,1)

p[ret,src,dst]#=>[:finished,"","i"]

#primitive_errinforeturnsimportantinformationregardingthelasterrorasa5-elementarray:

[result,enc1,enc2,error_bytes,readagain_bytes]

resultisthelastresultofprimitive_convert.

Otherelementsareonlymeaningfulwhenresultis:invalid_byte_sequence,:incomplete_inputor:undefined_conversion.

enc1andenc2indicateaconversionstepasapairofstrings.Forexample,aconverterfromEUC-JPtoISO-8859-1convertsastringasfollows:EUC-JP->UTF-8->ISO-8859-1.So[enc1,enc2]iseither[“EUC-JP”,“UTF-8”]or[“UTF-8”,“ISO-8859-1”].

error_bytesandreadagain_bytesindicatethebytesequenceswhichcausedtheerror.error_bytesisdiscardedportion.readagain_bytesisbufferedportionwhichisreadagainonnextconversion.

Example:

#\xffisinvalidasEUC-JP.

ec=Encoding::Converter.new("EUC-JP","Shift_JIS")

ec.primitive_convert(src="\xff",dst="",nil,10)

pec.primitive_errinfo

#=>[:invalid_byte_sequence,"EUC-JP","UTF-8","\xFF",""]

#HIRAGANALETTERA(\xa4\xa2inEUC-JP)isnotrepresentableinISO-8859-1.

#SincethiserrorisoccurinUTF-8toISO-8859-1conversion,

#error_bytesisHIRAGANALETTERAinUTF-8(\xE3\x81\x82).

ec=Encoding::Converter.new("EUC-JP","ISO-8859-1")

primitive_errinfo→array

Page 163: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ec.primitive_convert(src="\xa4\xa2",dst="",nil,10)

pec.primitive_errinfo

#=>[:undefined_conversion,"UTF-8","ISO-8859-1","\xE3\x81\x82",""]

#partialcharacterisinvalid

ec=Encoding::Converter.new("EUC-JP","ISO-8859-1")

ec.primitive_convert(src="\xa4",dst="",nil,10)

pec.primitive_errinfo

#=>[:incomplete_input,"EUC-JP","UTF-8","\xA4",""]

#Encoding::Converter::PARTIAL_INPUTpreventsinvaliderrorsby

#partialcharacters.

ec=Encoding::Converter.new("EUC-JP","ISO-8859-1")

ec.primitive_convert(src="\xa4",dst="",nil,10,Encoding

pec.primitive_errinfo

#=>[:source_buffer_empty,nil,nil,nil,nil]

#\xd8\x00\x00@isinvalidasUTF-16BEbecause

#nolowsurrogateafterhighsurrogate(\xd8\x00).

#Itisdetectedby3rdbyte(\00)whichispartofnextcharacter.

#Sothehighsurrogate(\xd8\x00)isdiscardedand

#the3rdbyteisreadagainlater.

#Sincethebyteisbufferedinec,itisdroppedfromsrc.

ec=Encoding::Converter.new("UTF-16BE","UTF-8")

ec.primitive_convert(src="\xd8\x00\x00@",dst="",nil,

pec.primitive_errinfo

#=>[:invalid_byte_sequence,"UTF-16BE","UTF-8","\xD8\x00","\x00"]

psrc

#=>"@"

#SimilartoUTF-16BE,\x00\xd8@\x00isinvalidasUTF-16LE.

#Theproblemisdetectedby4thbyte.

ec=Encoding::Converter.new("UTF-16LE","UTF-8")

ec.primitive_convert(src="\x00\xd8@\x00",dst="",nil,

pec.primitive_errinfo

#=>[:invalid_byte_sequence,"UTF-16LE","UTF-8","\x00\xD8","@\x00"]

psrc

#=>""

call-seq

ec.putback->string

ec.putback(max_numbytes)->string

putback(p1=v1)

Page 164: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Putbackthebyteswhichwillbeconverted.

Thebytesarecausedbyinvalid_byte_sequenceerror.Wheninvalid_byte_sequenceerror,somebytesarediscardedandsomebytesarebufferedtobeconvertedlater.Thelatterbytescanbeputback.ItcanbeobservedbyEncoding::InvalidByteSequenceError#readagain_bytesand#primitive_errinfo.

ec=Encoding::Converter.new("utf-16le","iso-8859-1")

src="\x00\xd8\x61\x00"

dst=""

pec.primitive_convert(src,dst)#=>:invalid_byte_sequence

pec.primitive_errinfo#=>[:invalid_byte_sequence,"UTF-16LE","UTF-8","\x00\xD8","a\x00"]

pec.putback#=>"a\x00"

pec.putback#=>""#nomorebytestoputback

Returnsthereplacementstring.

ec=Encoding::Converter.new("euc-jp","us-ascii")

pec.replacement#=>"?"

ec=Encoding::Converter.new("euc-jp","utf-8")

pec.replacement#=>"\uFFFD"

Setsthereplacementstring.

ec=Encoding::Converter.new("utf-8","us-ascii",:undef

ec.replacement="<undef>"

pec.convert("a\u3042b")#=>"a<undef>b"

replacement→string

replacement=string

source_encoding→encoding

Page 165: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsthesourceencodingasanEncodingobject.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 166: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEncoding::ConverterNotFoundErrorRaisedbytranscodingmethodswhenanamedencodingdoesnotcorrespondwithaknownconverter.

InFilesencoding.c

Parentrb_eEncodingError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 167: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEncoding::InvalidByteSequenceErrorRaisedbyEncodingandStringmethodswhenthestringbeingtranscodedcontainsabyteinvalidfortheeitherthesourceortargetencoding.

InFilesencoding.c

Parentrb_eEncodingError

PublicInstanceMethods

Returnsthedestinationencodingasanencodingobject.

Returnsthedestinationencodingnameasastring.

ReturnsthediscardedbyteswhenEncoding::InvalidByteSequenceErroroccurs.

destination_encoding→string

destination_encoding_name→string

error_bytes→string

Page 168: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ec=Encoding::Converter.new("EUC-JP","ISO-8859-1")

begin

ec.convert("abc\xA1\xFFdef")

rescueEncoding::InvalidByteSequenceError

p$!#=>#<Encoding::InvalidByteSequenceError:"\xA1"followedby"\xFF"onEUC-JP>

puts$!.error_bytes.dump#=>"\xA1"

puts$!.readagain_bytes.dump#=>"\xFF"

end

Returnstrueiftheinvalidbytesequenceerroriscausedbyprematureendofstring.

ec=Encoding::Converter.new("EUC-JP","ISO-8859-1")

begin

ec.convert("abc\xA1z")

rescueEncoding::InvalidByteSequenceError

p$!#=>#<Encoding::InvalidByteSequenceError:"\xA1"followedby"z"onEUC-JP>

p$!.incomplete_input?#=>false

end

begin

ec.convert("abc\xA1")

ec.finish

rescueEncoding::InvalidByteSequenceError

p$!#=>#<Encoding::InvalidByteSequenceError:incomplete"\xA1"onEUC-JP>

p$!.incomplete_input?#=>true

end

ReturnsthebytestobereadagainwhenEncoding::InvalidByteSequenceErroroccurs.

Returnsthesourceencodingasanencodingobject.

Notethattheresultmaynotbeequaltothesource

incomplete_input?→trueorfalse

readagain_bytes→string

source_encoding→encoding

Page 169: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

encodingoftheencodingconverteriftheconversionhasmultiplesteps.

ec=Encoding::Converter.new("ISO-8859-1","EUC-JP")#ISO-8859-1->UTF-8->EUC-JP

begin

ec.convert("\xa0")#NO-BREAKSPACE,whichisavailableinUTF-8butnotinEUC-JP.

rescueEncoding::UndefinedConversionError

p$!.source_encoding#=>#<Encoding:UTF-8>

p$!.destination_encoding#=>#<Encoding:EUC-JP>

p$!.source_encoding_name#=>"UTF-8"

p$!.destination_encoding_name#=>"EUC-JP"

end

Returnsthesourceencodingnameasastring.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

source_encoding_name→string

Page 170: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEncoding::UndefinedConversionErrorRaisedbyEncodingandStringmethodswhenatranscodingoperationfails.

InFilesencoding.c

Parentrb_eEncodingError

PublicInstanceMethods

Returnsthedestinationencodingasanencodingobject.

Returnsthedestinationencodingnameasastring.

Returnstheone-characterstringwhichcauseEncoding::UndefinedConversionError.

ec=Encoding::Converter.new("ISO-8859-1","EUC-JP")

begin

destination_encoding→string

destination_encoding_name→string

error_char→string

Page 171: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ec.convert("\xa0")

rescueEncoding::UndefinedConversionError

puts$!.error_char.dump#=>"\xC2\xA0"

p$!.error_char.encoding#=>#<Encoding:UTF-8>

end

Returnsthesourceencodingasanencodingobject.

Notethattheresultmaynotbeequaltothesourceencodingoftheencodingconverteriftheconversionhasmultiplesteps.

ec=Encoding::Converter.new("ISO-8859-1","EUC-JP")#ISO-8859-1->UTF-8->EUC-JP

begin

ec.convert("\xa0")#NO-BREAKSPACE,whichisavailableinUTF-8butnotinEUC-JP.

rescueEncoding::UndefinedConversionError

p$!.source_encoding#=>#<Encoding:UTF-8>

p$!.destination_encoding#=>#<Encoding:EUC-JP>

p$!.source_encoding_name#=>"UTF-8"

p$!.destination_encoding_name#=>"EUC-JP"

end

Returnsthesourceencodingnameasastring.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

source_encoding→encoding

source_encoding_name→string

Page 172: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEncodingErrorEncodingErroristhebaseclassforencodingerrors.

InFileserror.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 173: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleEnumerableTheEnumerablemixinprovidescollectionclasseswithseveraltraversalandsearchingmethods,andwiththeabilitytosort.Theclassmustprovideamethodeach,whichyieldssuccessivemembersofthecollection.IfEnumerable#max,#min,or#sortisused,theobjectsinthecollectionmustalsoimplementameaningful<=>operator,asthesemethodsrelyonanorderingbetweenmembersofthecollection.

InFilesenum.cenumerator.c

PublicInstanceMethods

Passeseachelementofthecollectiontothegivenblock.Themethodreturnstrueiftheblockneverreturnsfalseornil.Iftheblockisnotgiven,Rubyaddsanimplicitblockof{|obj|obj}whichwillcauseall?toreturntruewhennoneofthecollectionmembersarefalseornil.

%w[antbearcat].all?{|word|word.length>=3}#=>true

%w[antbearcat].all?{|word|word.length>=4}#=>false

[nil,true,99].all?#=>false

all?[{|obj|block}]→trueorfalse

Page 174: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Passeseachelementofthecollectiontothegivenblock.Themethodreturnstrueiftheblockeverreturnsavalueotherthanfalseornil.Iftheblockisnotgiven,Rubyaddsanimplicitblockof{|obj|obj}thatwillcauseany?toreturntrueifatleastoneofthecollectionmembersisnotfalseornil.

%w[antbearcat].any?{|word|word.length>=3}#=>true

%w[antbearcat].any?{|word|word.length>=4}#=>true

[nil,true,99].any?#=>true

Enumeratesovertheitems,chunkingthemtogetherbasedonthereturnvalueoftheblock.

Consecutiveelementswhichreturnthesameblockvaluearechunkedtogether.

Forexample,consecutiveevennumbersandoddnumberscanbechunkedasfollows.

[3,1,4,1,5,9,2,6,5,3,5].chunk{|n|

n.even?

}.each{|even,ary|

p[even,ary]

}

#=>[false,[3,1]]

#[true,[4]]

#[false,[1,5,9]]

#[true,[2,6]]

#[false,[5,3,5]]

Thismethodisespeciallyusefulforsortedseriesofelements.Thefollowingexamplecountswordsfor

any?[{|obj|block}]→trueorfalse

chunk{|elt|...}→an_enumeratorchunk(initial_state){|elt,state|...}→an_enumerator(deprecated)

Page 175: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

eachinitialletter.

open("/usr/share/dict/words","r:iso-8859-1"){|f|

f.chunk{|line|line.ord}.each{|ch,lines|p[ch

}

#=>["\n",1]

#["A",1327]

#["B",1372]

#["C",1507]

#["D",791]

#...

Thefollowingkeyvalueshavespecialmeaning:

niland:_separatorspecifiesthattheelementsshouldbedropped.

:_alonespecifiesthattheelementshouldbechunkedbyitself.

Anyothersymbolsthatbeginwithanunderscorewillraiseanerror:

items.chunk{|item|:_underscore}

#=>RuntimeError:symbolsbeginningwithanunderscorearereserved

niland:_separatorcanbeusedtoignoresomeelements.

Forexample,thesequenceofhyphensinsvnlogcanbeeliminatedasfollows:

sep="-"*72+"\n"

IO.popen("svnlogREADME"){|f|

f.chunk{|line|

line!=sep||nil

}.each{|_,lines|

pplines

}

}

#=>["r20018|knu|2008-10-2913:20:42+0900(Wed,29Oct2008)|2lines\n",

#"\n",

#"*README,README.ja:Updatetheportabilitysection.\n",

#"\n"]

Page 176: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#["r16725|knu|2008-05-3123:34:23+0900(Sat,31May2008)|2lines\n",

#"\n",

#"*README,README.ja:AddanoteaboutdefaultCflags.\n",

#"\n"]

#...

Paragraphsseparatedbyemptylinescanbeparsedasfollows:

File.foreach("README").chunk{|line|

/\A\s*\z/!~line||nil

}.each{|_,lines|

pplines

}

:_alonecanbeusedtoforceitemsintotheirownchunk.Forexample,youcanputlinesthatcontainaURLbythemselves,andchunktherestofthelinestogether,likethis:

pattern=/http/

open(filename){|f|

f.chunk{|line|line=~pattern?:_alone:true}.

pplines

}

}

Returnsanewarraywiththeresultsofrunningblockonceforeveryelementinenum.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

(1..4).map{|i|i*i}#=>[1,4,9,16]

(1..4).collect{"cat"}#=>["cat","cat","cat","cat"]

collect{|obj|block}→arraymap{|obj|block}→arraycollect→an_enumeratormap→an_enumerator

Page 177: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanewarraywiththeconcatenatedresultsofrunningblockonceforeveryelementinenum.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

[1,2,3,4].flat_map{|e|[e,-e]}#=>[1,-1,2,-2,3,-3,4,-4]

[[1,2],[3,4]].flat_map{|e|e+[100]}#=>[1,2,100,3,4,100]

Returnsthenumberofitemsinenumthroughenumeration.Ifanargumentisgiven,thenumberofitemsinenumthatareequaltoitemarecounted.Ifablockisgiven,itcountsthenumberofelementsyieldingatruevalue.

ary=[1,2,4,2]

ary.count#=>4

ary.count(2)#=>2

ary.count{|x|x%2==0}#=>3

Callsblockforeachelementofenumrepeatedlyntimesorforeverifnoneornilisgiven.Ifanon-positivenumberisgivenorthecollectionisempty,

flat_map{|obj|block}→arraycollect_concat{|obj|block}→arrayflat_map→an_enumeratorcollect_concat→an_enumerator

count→intcount(item)→intcount{|obj|block}→int

cycle(n=nil){|obj|block}→nilcycle(n=nil)→an_enumerator

Page 178: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

doesnothing.Returnsniliftheloophasfinishedwithoutgettinginterrupted.

#cyclesaveselementsinaninternalarraysochangestoenumafterthefirstpasshavenoeffect.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

a=["a","b","c"]

a.cycle{|x|putsx}#print,a,b,c,a,b,c,..forever.

a.cycle(2){|x|putsx}#print,a,b,c,a,b,c.

Passeseachentryinenumtoblock.Returnsthefirstforwhichblockisnotfalse.Ifnoobjectmatches,callsifnoneandreturnsitsresultwhenitisspecified,orreturnsnilotherwise.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

(1..10).detect{|i|i%5==0andi%7==0}#=>nil

(1..100).find{|i|i%5==0andi%7==0}#=>35

Dropsfirstnelementsfromenum,andreturnsrestelementsinanarray.

a=[1,2,3,4,5,0]

a.drop(3)#=>[4,5,0]

detect(ifnone=nil){|obj|block}→objornilfind(ifnone=nil){|obj|block}→objornildetect(ifnone=nil)→an_enumeratorfind(ifnone=nil)→an_enumerator

drop(n)→array

Page 179: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Dropselementsupto,butnotincluding,thefirstelementforwhichtheblockreturnsnilorfalseandreturnsanarraycontainingtheremainingelements.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

a=[1,2,3,4,5,0]

a.drop_while{|i|i<3}#=>[3,4,5,0]

Iteratesthegivenblockforeacharrayofconsecutive<n>elements.Ifnoblockisgiven,returnsanenumerator.

e.g.:

(1..10).each_cons(3){|a|pa}

#outputsbelow

[1,2,3]

[2,3,4]

[3,4,5]

[4,5,6]

[5,6,7]

[6,7,8]

[7,8,9]

[8,9,10]

Callsblockonceforeachelementinself,passingthatelementasaparameter,convertingmultiplevaluesfromyieldtoanarray.

Ifnoblockisgiven,anenumeratorisreturned

drop_while{|arr|block}→arraydrop_while→an_enumerator

each_cons(n){...}→nileach_cons(n)→an_enumerator

each_entry{|obj|block}→enumeach_entry→an_enumerator

Page 180: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

instead.

classFoo

includeEnumerable

defeach

yield1

yield1,2

yield

end

end

Foo.new.each_entry{|o|po}

produces:

1

[1,2]

nil

Iteratesthegivenblockforeachsliceof<n>elements.Ifnoblockisgiven,returnsanenumerator.

(1..10).each_slice(3){|a|pa}

#outputsbelow

[1,2,3]

[4,5,6]

[7,8,9]

[10]

Callsblockwithtwoarguments,theitemanditsindex,foreachiteminenum.Givenargumentsarepassedthroughtoeach().

Ifnoblockisgiven,anenumeratorisreturnedinstead.

each_slice(n){...}→nileach_slice(n)→an_enumerator

each_with_index(*args){|obj,i|block}→enumeach_with_index(*args)→an_enumerator

Page 181: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

hash=Hash.new

%w(catdogwombat).each_with_index{|item,index|

hash[item]=index

}

hash#=>{"cat"=>0,"dog"=>1,"wombat"=>2}

Iteratesthegivenblockforeachelementwithanarbitraryobjectgiven,andreturnstheinitiallygivenobject.

Ifnoblockisgiven,returnsanenumerator.

evens=(1..10).each_with_object([]){|i,a|a<<i*2

#=>[2,4,6,8,10,12,14,16,18,20]

Returnsanarraycontainingtheitemsinenum.

(1..7).to_a#=>[1,2,3,4,5,6,7]

{'a'=>1,'b'=>2,'c'=>3}.to_a#=>[["a",1],["b",2],["c",3]]

require'prime'

Prime.entries10#=>[2,3,5,7]

Passeseachentryinenumtoblock.Returnsthefirst

each_with_object(obj){|(*args),memo_obj|...}→objeach_with_object(obj)→an_enumerator

to_a(*args)→arrayentries(*args)→array

detect(ifnone=nil){|obj|block}→objornilfind(ifnone=nil){|obj|block}→objornildetect(ifnone=nil)→an_enumeratorfind(ifnone=nil)→an_enumerator

Page 182: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

forwhichblockisnotfalse.Ifnoobjectmatches,callsifnoneandreturnsitsresultwhenitisspecified,orreturnsnilotherwise.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

(1..10).detect{|i|i%5==0andi%7==0}#=>nil

(1..100).find{|i|i%5==0andi%7==0}#=>35

Returnsanarraycontainingallelementsofenumforwhichthegivenblockreturnsatruevalue.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

(1..10).find_all{|i|i%3==0}#=>[3,6,9]

[1,2,3,4,5].select{|num|num.even?}#=>[2,4]

Seealso#reject.

Compareseachentryinenumwithvalueorpassestoblock.Returnstheindexforthefirstforwhichtheevaluatedvalueisnon-false.Ifnoobjectmatches,returnsnil

Ifneitherblocknorargumentisgiven,anenumeratorisreturnedinstead.

find_all{|obj|block}→arrayselect{|obj|block}→arrayfind_all→an_enumeratorselect→an_enumerator

find_index(value)→intornilfind_index{|obj|block}→intornilfind_index→an_enumerator

Page 183: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(1..10).find_index{|i|i%5==0andi%7==0}

(1..100).find_index{|i|i%5==0andi%7==0}

(1..100).find_index(50)

Returnsthefirstelement,orthefirstnelements,oftheenumerable.Iftheenumerableisempty,thefirstformreturnsnil,andthesecondformreturnsanemptyarray.

%w[foobarbaz].first#=>"foo"

%w[foobarbaz].first(2)#=>["foo","bar"]

%w[foobarbaz].first(10)#=>["foo","bar","baz"]

[].first#=>nil

Returnsanewarraywiththeconcatenatedresultsofrunningblockonceforeveryelementinenum.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

[1,2,3,4].flat_map{|e|[e,-e]}#=>[1,-1,2,-2,3,-3,4,-4]

[[1,2],[3,4]].flat_map{|e|e+[100]}#=>[1,2,100,3,4,100]

ReturnsanarrayofeveryelementinenumforwhichPattern===element.Iftheoptionalblockissupplied,

first→objornilfirst(n)→an_array

flat_map{|obj|block}→arraycollect_concat{|obj|block}→arrayflat_map→an_enumeratorcollect_concat→an_enumerator

grep(pattern)→arraygrep(pattern){|obj|block}→array

Page 184: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

eachmatchingelementispassedtoit,andtheblock'sresultisstoredintheoutputarray.

(1..100).grep38..44#=>[38,39,40,41,42,43,44]

c=IO.constants

c.grep(/SEEK/)#=>[:SEEK_SET,:SEEK_CUR,:SEEK_END]

res=c.grep(/SEEK/){|v|IO.const_get(v)}

res#=>[0,1,2]

Groupsthecollectionbyresultoftheblock.Returnsahashwherethekeysaretheevaluatedresultfromtheblockandthevaluesarearraysofelementsinthecollectionthatcorrespondtothekey.

Ifnoblockisgivenanenumeratorisreturned.

(1..6).group_by{|i|i%3}#=>{0=>[3,6],1=>[1,4],2=>[2,5]}

Returnstrueifanymemberofenumequalsobj.Equalityistestedusing==.

IO.constants.include?:SEEK_SET#=>true

IO.constants.include?:SEEK_NO_FURTHER#=>false

group_by{|obj|block}→a_hashgroup_by→an_enumerator

include?(obj)→trueorfalsemember?(obj)→trueorfalse

inject(initial,sym)→objinject(sym)→objinject(initial){|memo,obj|block}→objinject{|memo,obj|block}→objreduce(initial,sym)→obj

Page 185: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Combinesallelementsofenumbyapplyingabinaryoperation,specifiedbyablockorasymbolthatnamesamethodoroperator.

Ifyouspecifyablock,thenforeachelementinenumtheblockispassedanaccumulatorvalue(memo)andtheelement.Ifyouspecifyasymbolinstead,theneachelementinthecollectionwillbepassedtothenamedmethodofmemo.Ineithercase,theresultbecomesthenewvalueformemo.Attheendoftheiteration,thefinalvalueofmemoisthereturnvalueforthemethod.

Ifyoudonotexplicitlyspecifyaninitialvalueformemo,thenthefirstelementofcollectionisusedastheinitialvalueofmemo.

#Sumsomenumbers

(5..10).reduce(:+)#=>45

#Sameusingablockandinject

(5..10).inject{|sum,n|sum+n}#=>45

#Multiplysomenumbers

(5..10).reduce(1,:*)#=>151200

#Sameusingablock

(5..10).inject(1){|product,n|product*n}#=>151200

#findthelongestword

longest=%w{catsheepbear}.injectdo|memo,word|

memo.length>word.length?memo:word

end

longest#=>"sheep"

Returnsalazyenumerator,whosemethodsmap/collect,flat_map/collect_concat,select/find_all,reject,grep,zip,take,#take_while,drop,and#drop_whileenumeratevaluesonlyonanas-needed

reduce(sym)→objreduce(initial){|memo,obj|block}→objreduce{|memo,obj|block}→obj

lazy→lazy_enumerator

Page 186: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

basis.However,ifablockisgiventozip,valuesareenumeratedimmediately.

ExampleThefollowingprogramfindspythagoreantriples:

defpythagorean_triples

(1..Float::INFINITY).lazy.flat_map{|z|

(1..z).flat_map{|x|

(x..z).select{|y|

x**2+y**2==z**2

}.map{|y|

[x,y,z]

}

}

}

end

#showfirsttenpythagoreantriples

ppythagorean_triples.take(10).force#takeislazy,soforceisneeded

ppythagorean_triples.first(10)#firstiseager

#showpythagoreantripleslessthan100

ppythagorean_triples.take_while{|*,z|z<100}.force

Returnsanewarraywiththeresultsofrunningblockonceforeveryelementinenum.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

(1..4).map{|i|i*i}#=>[1,4,9,16]

(1..4).collect{"cat"}#=>["cat","cat","cat","cat"]

collect{|obj|block}→arraymap{|obj|block}→arraycollect→an_enumeratormap→an_enumerator

max→obj

Page 187: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheobjectinenumwiththemaximumvalue.ThefirstformassumesallobjectsimplementComparable;thesecondusestheblocktoreturna<=>b.

a=%w(albatrossdoghorse)

a.max#=>"horse"

a.max{|a,b|a.length<=>b.length}#=>"albatross"

Ifthenargumentisgiven,maximumnelementsarereturnedasanarray.

a=%w[albatrossdoghorse]

a.max(2)#=>["horse","dog"]

a.max(2){|a,b|a.length<=>b.length}#=>["albatross","horse"]

Returnstheobjectinenumthatgivesthemaximumvaluefromthegivenblock.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

a=%w(albatrossdoghorse)

a.max_by{|x|x.length}#=>"albatross"

Ifthenargumentisgiven,minimumnelementsarereturnedasanarray.

a=%w[albatrossdoghorse]

a.max_by(2){|x|x.length}#=>["albatross","horse"]

max{|a,b|block}→objmax(n)→objmax(n){|a,b|block}→obj

max_by{|obj|block}→objmax_by→an_enumeratormax_by(n){|obj|block}→objmax_by(n)→an_enumerator

Page 188: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

enum.max_by(n)canbeusedtoimplementweightedrandomsampling.FollowingexampleimplementsanduseEnumerable#wsample.

moduleEnumerable

#weightedrandomsampling.

#

#PavlosS.Efraimidis,PaulG.Spirakis

#Weightedrandomsamplingwithareservoir

#InformationProcessingLetters

#Volume97,Issue5(16March2006)

defwsample(n)

self.max_by(n){|v|rand**(1.0/yield(v))}

end

end

e=(-20..20).to_a*10000

a=e.wsample(20000){|x|

Math.exp(-(x/5.0)**2)#normaldistribution

}

#ais20000samplesfrome.

pa.length#=>20000

h=a.group_by{|x|x}

-10.upto(10){|x|puts"*"*(h[x].length/30.0).to_iif

#=>*

#***

#******

#***********

#******************

#*****************************

#*****************************************

#****************************************************

#***************************************************************

#********************************************************************

#***********************************************************************

#***********************************************************************

#**************************************************************

#****************************************************

#***************************************

#***************************

#******************

#***********

#*******

#***

#*

Page 189: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifanymemberofenumequalsobj.Equalityistestedusing==.

IO.constants.include?:SEEK_SET#=>true

IO.constants.include?:SEEK_NO_FURTHER#=>false

Returnstheobjectinenumwiththeminimumvalue.ThefirstformassumesallobjectsimplementComparable;thesecondusestheblocktoreturna<=>b.

a=%w(albatrossdoghorse)

a.min#=>"albatross"

a.min{|a,b|a.length<=>b.length}#=>"dog"

Ifthenargumentisgiven,minimumnelementsarereturnedasanarray.

a=%w[albatrossdoghorse]

a.min(2)#=>["albatross","dog"]

a.min(2){|a,b|a.length<=>b.length}#=>["dog","horse"]

include?(obj)→trueorfalsemember?(obj)→trueorfalse

min→objmin{|a,b|block}→objmin(n)→arraymin(n){|a,b|block}→array

min_by{|obj|block}→objmin_by→an_enumeratormin_by(n){|obj|block}→arraymin_by(n)→an_enumerator

Page 190: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheobjectinenumthatgivestheminimumvaluefromthegivenblock.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

a=%w(albatrossdoghorse)

a.min_by{|x|x.length}#=>"dog"

Ifthenargumentisgiven,minimumnelementsarereturnedasanarray.

a=%w[albatrossdoghorse]

pa.min_by(2){|x|x.length}#=>["dog","horse"]

Returnstwoelementsarraywhichcontainstheminimumandthemaximumvalueintheenumerable.ThefirstformassumesallobjectsimplementComparable;thesecondusestheblocktoreturna<=>b.

a=%w(albatrossdoghorse)

a.minmax#=>["albatross","horse"]

a.minmax{|a,b|a.length<=>b.length}#=>["dog","albatross"]

Returnsatwoelementarraycontainingtheobjectsinenumthatcorrespondtotheminimumandmaximumvaluesrespectivelyfromthegivenblock.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

a=%w(albatrossdoghorse)

minmax→[min,max]minmax{|a,b|block}→[min,max]

minmax_by{|obj|block}→[min,max]minmax_by→an_enumerator

Page 191: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a.minmax_by{|x|x.length}#=>["dog","albatross"]

Passeseachelementofthecollectiontothegivenblock.Themethodreturnstrueiftheblockneverreturnstrueforallelements.Iftheblockisnotgiven,none?willreturntrueonlyifnoneofthecollectionmembersistrue.

%w{antbearcat}.none?{|word|word.length==5}#=>true

%w{antbearcat}.none?{|word|word.length>=4}#=>false

[].none?#=>true

[nil].none?#=>true

[nil,false].none?#=>true

Passeseachelementofthecollectiontothegivenblock.Themethodreturnstrueiftheblockreturnstrueexactlyonce.Iftheblockisnotgiven,one?willreturntrueonlyifexactlyoneofthecollectionmembersistrue.

%w{antbearcat}.one?{|word|word.length==4}#=>true

%w{antbearcat}.one?{|word|word.length>4}#=>false

%w{antbearcat}.one?{|word|word.length<4}#=>false

[nil,true,99].one?#=>false

[nil,true,false].one?#=>true

Returnstwoarrays,thefirstcontainingtheelementsofenumforwhichtheblockevaluatestotrue,the

none?[{|obj|block}]→trueorfalse

one?[{|obj|block}]→trueorfalse

partition{|obj|block}→[true_array,false_array]partition→an_enumerator

Page 192: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

secondcontainingtherest.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

(1..6).partition{|v|v.even?}#=>[[2,4,6],[1,3,5]]

Combinesallelementsofenumbyapplyingabinaryoperation,specifiedbyablockorasymbolthatnamesamethodoroperator.

Ifyouspecifyablock,thenforeachelementinenumtheblockispassedanaccumulatorvalue(memo)andtheelement.Ifyouspecifyasymbolinstead,theneachelementinthecollectionwillbepassedtothenamedmethodofmemo.Ineithercase,theresultbecomesthenewvalueformemo.Attheendoftheiteration,thefinalvalueofmemoisthereturnvalueforthemethod.

Ifyoudonotexplicitlyspecifyaninitialvalueformemo,thenthefirstelementofcollectionisusedastheinitialvalueofmemo.

#Sumsomenumbers

(5..10).reduce(:+)#=>45

#Sameusingablockandinject

(5..10).inject{|sum,n|sum+n}#=>45

#Multiplysomenumbers

inject(initial,sym)→objinject(sym)→objinject(initial){|memo,obj|block}→objinject{|memo,obj|block}→objreduce(initial,sym)→objreduce(sym)→objreduce(initial){|memo,obj|block}→objreduce{|memo,obj|block}→obj

Page 193: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(5..10).reduce(1,:*)#=>151200

#Sameusingablock

(5..10).inject(1){|product,n|product*n}#=>151200

#findthelongestword

longest=%w{catsheepbear}.injectdo|memo,word|

memo.length>word.length?memo:word

end

longest#=>"sheep"

Returnsanarrayforallelementsofenumforwhichthegivenblockreturnsfalse.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

(1..10).reject{|i|i%3==0}#=>[1,2,4,5,7,8,10]

[1,2,3,4,5].reject{|num|num.even?}#=>[1,3,5]

Seealso#find_all.

Buildsatemporaryarrayandtraversesthatarrayinreverseorder.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

(1..3).reverse_each{|v|pv}

produces:

3

2

1

reject{|obj|block}→arrayreject→an_enumerator

reverse_each(*args){|item|block}→enumreverse_each(*args)→an_enumerator

Page 194: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanarraycontainingallelementsofenumforwhichthegivenblockreturnsatruevalue.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

(1..10).find_all{|i|i%3==0}#=>[3,6,9]

[1,2,3,4,5].select{|num|num.even?}#=>[2,4]

Seealso#reject.

Createsanenumeratorforeachchunkedelements.Theendsofchunksaredefinedbypatternandtheblock.

Ifpattern===eltreturnstrueortheblockreturnstruefortheelement,theelementisendofachunk.

The===andblockiscalledfromthefirstelementtothelastelementofenum.

Theresultenumeratoryieldsthechunkedelementsasanarray.Soeachmethodcanbecalledasfollows:

enum.slice_after(pattern).each{|ary|...}

enum.slice_after{|elt|bool}.each{|ary|...}

OthermethodsoftheEnumeratorclassandEnumerablemodule,suchasmap,etc.,arealso

find_all{|obj|block}→arrayselect{|obj|block}→arrayfind_all→an_enumeratorselect→an_enumerator

slice_after(pattern)→an_enumeratorslice_after{|elt|bool}→an_enumerator

Page 195: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

usable.

Forexample,continuationlines(linesendwithbackslash)canbeconcatenatedasfollows:

lines=["foo\n","bar\\\n","baz\n","\n","qux\n"]

e=lines.slice_after(/(?<!\)\n\z/)

pe.to_a

#=>[["foo\n"],["bar\\\n","baz\n"],["\n"],["qux\n"]]

pe.map{|ll|ll[0...-1].map{|l|l.sub(/\\n\z/,"")}.

#=>["foo\n","barbaz\n","\n","qux\n"]

Createsanenumeratorforeachchunkedelements.Thebeginningsofchunksaredefinedbypatternandtheblock.

Ifpattern===eltreturnstrueortheblockreturnstruefortheelement,theelementisbeginningofachunk.

The===andblockiscalledfromthefirstelementtothelastelementofenum.Theresultforthefirstelementisignored.

Theresultenumeratoryieldsthechunkedelementsasanarray.Soeachmethodcanbecalledasfollows:

enum.slice_before(pattern).each{|ary|...}

enum.slice_before{|elt|bool}.each{|ary|...}

OthermethodsoftheEnumeratorclassandEnumerablemodule,suchasmap,etc.,arealsousable.

Forexample,iterationoverChangeLogentriescan

slice_before(pattern)→an_enumeratorslice_before{|elt|bool}→an_enumeratorslice_before(initial_state){|elt,state|bool}→an_enumerator(deprecated)

Page 196: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

beimplementedasfollows:

#iterateoverChangeLogentries.

open("ChangeLog"){|f|

f.slice_before(/\A\S/).each{|e|ppe}

}

#sameasabove.blockisusedinsteadofpatternargument.

open("ChangeLog"){|f|

f.slice_before{|line|/\A\S/===line}.each{|e|

}

“svnproplist-R”producesmultilineoutputforeachfile.Theycanbechunkedasfollows:

IO.popen([{"LC_ALL"=>"C"},"svn","proplist","-R"]){

f.lines.slice_before(/\AProp/).each{|lines|plines

}

#=>["Propertieson'.':\n","svn:ignore\n","svk:merge\n"]

#["Propertieson'goruby.c':\n","svn:eol-style\n"]

#["Propertieson'complex.c':\n","svn:mime-type\n","svn:eol-style\n"]

#["Propertieson'regparse.c':\n","svn:eol-style\n"]

#...

Iftheblockneedstomaintainstateovermultipleelements,localvariablescanbeused.Forexample,threeormoreconsecutiveincreasingnumberscanbesquashedasfollows:

a=[0,2,3,4,6,7,9]

prev=a[0]

pa.slice_before{|e|

prev,prev2=e,prev

prev2+1!=e

}.map{|es|

es.length<=2?es.join(","):"#{es.first}-#{es.last}"

}.join(",")

#=>"0,2-4,6,7,9"

Howeverlocalvariablesshouldbeusedcarefullyiftheresultenumeratorisenumeratedtwiceormore.Thelocalvariablesshouldbeinitializedforeach

Page 197: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

enumeration.Enumerator.newcanbeusedtodoit.

#Wordwrapping.Thisassumesallcharactershavesamewidth.

defwordwrap(words,maxwidth)

Enumerator.new{|y|

#colsisinitializedinEnumerator.new.

cols=0

words.slice_before{|w|

cols+=1ifcols!=0

cols+=w.length

ifmaxwidth<cols

cols=w.length

true

else

false

end

}.each{|ws|y.yieldws}

}

end

text=(1..20).to_a.join("")

enum=wordwrap(text.split(/\s+/),10)

puts"-"*10

enum.each{|ws|putsws.join("")}#firstenumeration.

puts"-"*10

enum.each{|ws|putsws.join("")}#secondenumerationgeneratessameresultasthefirst.

puts"-"*10

#=>----------

#12345

#678910

#111213

#141516

#171819

#20

#----------

#12345

#678910

#111213

#141516

#171819

#20

#----------

mboxcontainsseriesofmailswhichstartwithUnixFromline.SoeachmailcanbeextractedbyslicebeforeUnixFromline.

Page 198: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#parsembox

open("mbox"){|f|

f.slice_before{|line|

line.start_with?"From"

}.each{|mail|

unix_from=mail.shift

i=mail.index("\n")

header=mail[0...i]

body=mail[(i+1)..-1]

body.popifbody.last=="\n"

fields=header.slice_before{|line|!"\t".include?

punix_from

ppfields

ppbody

}

}

#splitmailsinmbox(slicebeforeUnixFromlineafteranemptyline)

open("mbox"){|f|

f.slice_before(emp:true){|line,h|

prevemp=h[:emp]

h[:emp]=line=="\n"

prevemp&&line.start_with?("From")

}.each{|mail|

mail.popifmail.last=="\n"

ppmail

}

}

Createsanenumeratorforeachchunkedelements.Thebeginningsofchunksaredefinedbytheblock.

Thismethodspliteachchunkusingadjacentelements,elt_beforeandelt_after,inthereceiverenumerator.Thismethodsplitchunksbetweenelt_beforeandelt_afterwheretheblockreturnstrue.

Theblockiscalledthelengthofthereceiverenumeratorminusone.

slice_when{|elt_before,elt_after|bool}→an_enumerator

Page 199: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Theresultenumeratoryieldsthechunkedelementsasanarray.Soeachmethodcanbecalledasfollows:

enum.slice_when{|elt_before,elt_after|bool}.each{

OthermethodsoftheEnumeratorclassandEnumerablemodule,suchasto_a,map,etc.,arealsousable.

Forexample,one-by-oneincreasingsubsequencecanbechunkedasfollows:

a=[1,2,4,9,10,11,12,15,16,19,20,21]

b=a.slice_when{|i,j|i+1!=j}

pb.to_a#=>[[1,2],[4],[9,10,11,12],[15,16],[19,20,21]]

c=b.map{|a|a.length<3?a:"#{a.first}-#{a.last}"

pc#=>[[1,2],[4],"9-12",[15,16],"19-21"]

d=c.join(",")

pd#=>"1,2,4,9-12,15,16,19-21"

Nearelements(threshold:6)insortedarraycanbechunkedasfollwos:

a=[3,11,14,25,28,29,29,41,55,57]

pa.slice_when{|i,j|6<j-i}.to_a

#=>[[3],[11,14],[25,28,29,29],[41],[55,57]]

Increasing(non-decreasing)subsequencecanbechunkedasfollows:

a=[0,9,2,2,3,2,7,5,9,5]

pa.slice_when{|i,j|i>j}.to_a

#=>[[0,9],[2,2,3],[2,7],[5,9],[5]]

Adjacentevensandoddscanbechunkedasfollows:(#chunkisanotherwaytodoit.)

a=[7,5,9,2,0,7,9,4,2,0]

pa.slice_when{|i,j|i.even?!=j.even?}.to_a

#=>[[7,5,9],[2,0],[7,9],[4,2,0]]

Page 200: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Paragraphs(non-emptylineswithtrailingemptylines)canbechunkedasfollows:(See#chunktoignoreemptylines.)

lines=["foo\n","bar\n","\n","baz\n","qux\n"]

plines.slice_when{|l1,l2|/\A\s*\z/=~l1&&/\S/=~

#=>[["foo\n","bar\n","\n"],["baz\n","qux\n"]]

Returnsanarraycontainingtheitemsinenumsorted,eitheraccordingtotheirown<=>method,orbyusingtheresultsofthesuppliedblock.Theblockshouldreturn-1,0,or+1dependingonthecomparisonbetweenaandb.AsofRuby1.8,themethodEnumerable#sort_byimplementsabuilt-inSchwartzianTransform,usefulwhenkeycomputationorcomparisonisexpensive.

%w(rheakeaflea).sort#=>["flea","kea","rhea"]

(1..10).sort{|a,b|b<=>a}#=>[10,9,8,7,6,5,4,3,2,1]

Sortsenumusingasetofkeysgeneratedbymappingthevaluesinenumthroughthegivenblock.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

%w{applepearfig}.sort_by{|word|word.length}

#=>["fig","pear","apple"]

Thecurrentimplementationofsort_bygeneratesanarrayoftuplescontainingtheoriginalcollection

sort→arraysort{|a,b|block}→array

sort_by{|obj|block}→arraysort_by→an_enumerator

Page 201: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

elementandthemappedvalue.Thismakessort_byfairlyexpensivewhenthekeysetsaresimple.

require'benchmark'

a=(1..100000).map{rand(100000)}

Benchmark.bm(10)do|b|

b.report("Sort"){a.sort}

b.report("Sortby"){a.sort_by{|a|a}}

end

produces:

usersystemtotalreal

Sort0.1800000.0000000.180000(0.175469)

Sortby1.9800000.0400002.020000(2.013586)

However,considerthecasewherecomparingthekeysisanon-trivialoperation.Thefollowingcodesortssomefilesonmodificationtimeusingthebasicsortmethod.

files=Dir["*"]

sorted=files.sort{|a,b|File.new(a).mtime<=>File

sorted#=>["mon","tues","wed","thurs"]

Thissortisinefficient:itgeneratestwonewFileobjectsduringeverycomparison.AslightlybettertechniqueistousetheKernel#testmethodtogeneratethemodificationtimesdirectly.

files=Dir["*"]

sorted=files.sort{|a,b|

test(M,a)<=>test(M,b)

}

sorted#=>["mon","tues","wed","thurs"]

ThisstillgeneratesmanyunnecessaryTimeobjects.Amoreefficienttechniqueistocachethesortkeys(modificationtimesinthiscase)beforethesort.Perl

Page 202: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

usersoftencallthisapproachaSchwartzianTransform,afterRandalSchwartz.Weconstructatemporaryarray,whereeachelementisanarraycontainingoursortkeyalongwiththefilename.Wesortthisarray,andthenextractthefilenamefromtheresult.

sorted=Dir["*"].collect{|f|

[test(M,f),f]

}.sort.collect{|f|f[1]}

sorted#=>["mon","tues","wed","thurs"]

Thisisexactlywhatsort_bydoesinternally.

sorted=Dir["*"].sort_by{|f|test(M,f)}

sorted#=>["mon","tues","wed","thurs"]

Returnsfirstnelementsfromenum.

a=[1,2,3,4,5,0]

a.take(3)#=>[1,2,3]

a.take(30)#=>[1,2,3,4,5,0]

Passeselementstotheblockuntiltheblockreturnsnilorfalse,thenstopsiteratingandreturnsanarrayofallpriorelements.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

a=[1,2,3,4,5,0]

a.take_while{|i|i<3}#=>[1,2]

take(n)→array

take_while{|arr|block}→arraytake_while→an_enumerator

to_a(*args)→array

Page 203: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanarraycontainingtheitemsinenum.

(1..7).to_a#=>[1,2,3,4,5,6,7]

{'a'=>1,'b'=>2,'c'=>3}.to_a#=>[["a",1],["b",2],["c",3]]

require'prime'

Prime.entries10#=>[2,3,5,7]

Returnstheresultofinterpretingenumasalistof[key,value]pairs.

%[helloworld].each_with_index.to_h

#=>{:hello=>0,:world=>1}

Takesoneelementfromenumandmergescorrespondingelementsfromeachargs.Thisgeneratesasequenceofn-elementarrays,wherenisonemorethanthecountofarguments.Thelengthoftheresultingsequencewillbeenum#size.Ifthesizeofanyargumentislessthanenum#size,nilvaluesaresupplied.Ifablockisgiven,itisinvokedforeachoutputarray,otherwiseanarrayofarraysisreturned.

a=[4,5,6]

b=[7,8,9]

a.zip(b)#=>[[4,7],[5,8],[6,9]]

[1,2,3].zip(a,b)#=>[[1,4,7],[2,5,8],[3,6,9]]

[1,2].zip(a,b)#=>[[1,4,7],[2,5,8]]

a.zip([1,2],[8])#=>[[4,1,8],[5,2,nil],[6,nil,nil]]

entries(*args)→array

to_h(*args)→hash

zip(arg,...)→an_array_of_arrayzip(arg,...){|arr|block}→nil

Page 204: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 205: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEnumeratorAclasswhichallowsbothinternalandexternaliteration.

AnEnumeratorcanbecreatedbythefollowingmethods.

Kernel#to_enumKernel#enum_for::new

Mostmethodshavetwoforms:ablockformwherethecontentsareevaluatedforeachitemintheenumeration,andanon-blockformwhichreturnsanewEnumeratorwrappingtheiteration.

enumerator=%w(onetwothree).each

putsenumerator.class#=>Enumerator

enumerator.each_with_object("foo")do|item,obj|

puts"#{obj}:#{item}"

end

#foo:one

#foo:two

#foo:three

enum_with_obj=enumerator.each_with_object("foo"

putsenum_with_obj.class#=>Enumerator

enum_with_obj.eachdo|item,obj|

puts"#{obj}:#{item}"

Page 206: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

#foo:one

#foo:two

#foo:three

ThisallowsyoutochainEnumeratorstogether.Forexample,youcanmapalist'selementstostringscontainingtheindexandtheelementasastringvia:

puts%w[foobarbaz].map.with_index{|w,i|"#{i}:#{w}"

#=>["0:foo","1:bar","2:baz"]

AnEnumeratorcanalsobeusedasanexternaliterator.Forexample,#nextreturnsthenextvalueoftheiteratororraisesStopIterationiftheEnumeratorisattheend.

e=[1,2,3].each#returnsanenumeratorobject.

putse.next#=>1

putse.next#=>2

putse.next#=>3

putse.next#raisesStopIteration

Youcanusethistoimplementaninternaliteratorasfollows:

defext_each(e)

whiletrue

begin

vs=e.next_values

rescueStopIteration

return$!.result

Page 207: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

y=yield(*vs)

e.feedy

end

end

o=Object.new

defo.each

putsyield

putsyield(1)

putsyield(1,2)

3

end

#useo.eachasaninternaliteratordirectly.

putso.each{|*x|putsx;[:b,*x]}

#=>[],[:b],[1],[:b,1],[1,2],[:b,1,2],3

#converto.eachtoanexternaliteratorfor

#implementinganinternaliterator.

putsext_each(o.to_enum){|*x|putsx;[:b,*x]}

#=>[],[:b],[1],[:b,1],[1,2],[:b,1,2],3

InFilesenumerator.c

ParentObject

IncludedModulesEnumerable

Page 208: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PublicClassMethods

CreatesanewEnumeratorobject,whichcanbeusedasanEnumerable.

Inthefirstform,iterationisdefinedbythegivenblock,inwhicha“yielder”object,givenasblockparameter,canbeusedtoyieldavaluebycallingtheyieldmethod(aliasedas+<<+):

fib=Enumerator.newdo|y|

a=b=1

loopdo

y<<a

a,b=b,a+b

end

end

pfib.take(10)#=>[1,1,2,3,5,8,13,21,34,55]

Theoptionalparametercanbeusedtospecifyhowtocalculatethesizeinalazyfashion(see#size).Itcaneitherbeavalueoracallableobject.

Inthesecond,deprecated,form,ageneratedEnumeratoriteratesoverthegivenobjectusingthegivenmethodwiththegivenargumentspassed.

Useofthisformisdiscouraged.UseKernel#enum_fororKernel#to_enuminstead.

e=Enumerator.new(ObjectSpace,:each_object)

#->ObjectSpace.enum_for(:each_object)

e.select{|obj|obj.is_a?(Class)}#=>arrayofallclasses

new(size=nil){|yielder|...}new(obj,method=:each,*args)

Page 209: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PublicInstanceMethods

IteratesovertheblockaccordingtohowthisEnumeratorwasconstructed.Ifnoblockandnoargumentsaregiven,returnsself.

Examples"Hello,world!".scan(/\w+/)#=>["Hello","world"]

"Hello,world!".to_enum(:scan,/\w+/).to_a#=>["Hello","world"]

"Hello,world!".to_enum(:scan).each(/\w+/).to_a#=>["Hello","world"]

obj=Object.new

defobj.each_arg(a,b=:b,*rest)

yielda

yieldb

yieldrest

:method_returned

end

enum=obj.to_enum:each_arg,:a,:x

enum.each.to_a#=>[:a,:x,[]]

enum.each.equal?(enum)#=>true

enum.each{|elm|elm}#=>:method_returned

enum.each(:y,:z).to_a#=>[:a,:x,[:y,:z]]

enum.each(:y,:z).equal?(enum)#=>false

enum.each(:y,:z){|elm|elm}#=>:method_returned

Sameas#with_index,i.e.thereisnostartingoffset.

each{|elm|block}→objeach→enumeach(*appending_args){|elm|block}→objeach(*appending_args)→an_enumerator

each_with_index{|(*args),idx|...}each_with_index

Page 210: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ifnoblockisgiven,anewEnumeratorisreturnedthatincludestheindex.

Iteratesthegivenblockforeachelementwithanarbitraryobject,obj,andreturnsobj

Ifnoblockisgiven,returnsanewEnumerator.

Exampleto_three=Enumerator.newdo|y|

3.timesdo|x|

y<<x

end

end

to_three_with_string=to_three.with_object("foo")

to_three_with_string.eachdo|x,string|

puts"#{string}:#{x}"

end

#=>foo:0

#=>foo:1

#=>foo:2

Setsthevaluetobereturnedbythenextyieldinsidee.

Ifthevalueisnotset,theyieldreturnsnil.

Thisvalueisclearedafterbeingyielded.

#Array#mappassesthearray'selementsto"yield"andcollectsthe

each_with_object(obj){|(*args),obj|...}each_with_object(obj)with_object(obj){|(*args),obj|...}with_object(obj)

feedobj→nil

Page 211: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#resultsof"yield"asanarray.

#Followingexampleshowsthat"next"returnsthepassedelementsand

#valuespassedto"feed"arecollectedasanarraywhichcanbe

#obtainedbyStopIteration#result.

e=[1,2,3].map

pe.next#=>1

e.feed"a"

pe.next#=>2

e.feed"b"

pe.next#=>3

e.feed"c"

begin

e.next

rescueStopIteration

p$!.result#=>["a","b","c"]

end

o=Object.new

defo.each

x=yield#(2)blocks

px#(5)=>"foo"

x=yield#(6)blocks

px#(8)=>nil

x=yield#(9)blocks

px#notreachedw/oanothere.next

end

e=o.to_enum

e.next#(1)

e.feed"foo"#(3)

e.next#(4)

e.next#(7)

#(10)

Createsaprintableversionofe.

Returnsthenextobjectintheenumerator,andmovetheinternalpositionforward.Whenthepositionreachedattheend,StopIterationisraised.

inspect→string

next→object

Page 212: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Examplea=[1,2,3]

e=a.to_enum

pe.next#=>1

pe.next#=>2

pe.next#=>3

pe.next#raisesStopIteration

Notethatenumerationsequencebynextdoesnotaffectothernon-externalenumerationmethods,unlesstheunderlyingiterationmethodsitselfhasside-effect,e.g.IO#each_line.

Returnsthenextobjectasanarrayintheenumerator,andmovetheinternalpositionforward.Whenthepositionreachedattheend,StopIterationisraised.

Thismethodcanbeusedtodistinguishyieldandyieldnil.

Exampleo=Object.new

defo.each

yield

yield1

yield1,2

yieldnil

yield[1,2]

end

e=o.to_enum

pe.next_values

pe.next_values

pe.next_values

pe.next_values

pe.next_values

e=o.to_enum

pe.next

next_values→array

Page 213: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

pe.next

pe.next

pe.next

pe.next

##yieldargsnext_valuesnext

#yield[]nil

#yield1[1]1

#yield1,2[1,2][1,2]

#yieldnil[nil]nil

#yield[1,2][[1,2]][1,2]

Notethatnext_valuesdoesnotaffectothernon-externalenumerationmethodsunlessunderlyingiterationmethoditselfhasside-effect,e.g.IO#each_line.

Returnsthenextobjectintheenumerator,butdoesn'tmovetheinternalpositionforward.Ifthepositionisalreadyattheend,StopIterationisraised.

Examplea=[1,2,3]

e=a.to_enum

pe.next#=>1

pe.peek#=>2

pe.peek#=>2

pe.peek#=>2

pe.next#=>2

pe.next#=>3

pe.peek#raisesStopIteration

Returnsthenextobjectasanarray,similarto#next_values,butdoesn'tmovetheinternalpositionforward.Ifthepositionisalreadyattheend,StopIterationisraised.

peek→object

peek_values→array

Page 214: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Exampleo=Object.new

defo.each

yield

yield1

yield1,2

end

e=o.to_enum

pe.peek_values#=>[]

e.next

pe.peek_values#=>[1]

pe.peek_values#=>[1]

e.next

pe.peek_values#=>[1,2]

e.next

pe.peek_values#raisesStopIteration

Rewindstheenumerationsequencetothebeginning.

Iftheenclosedobjectrespondstoa“rewind”method,itiscalled.

Returnsthesizeoftheenumerator,ornilifitcan'tbecalculatedlazily.

(1..100).to_a.permutation(4).size#=>94109400

loop.size#=>Float::INFINITY

(1..100).drop_while.size#=>nil

Iteratesthegivenblockforeachelementwithanindex,whichstartsfromoffset.Ifnoblockisgiven,returnsanewEnumeratorthatincludestheindex,startingfromoffset

rewind→e

size→int,Float::INFINITYornil

with_index(offset=0){|(*args),idx|...}with_index(offset=0)

Page 215: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

offset

thestartingindextouse

Iteratesthegivenblockforeachelementwithanarbitraryobject,obj,andreturnsobj

Ifnoblockisgiven,returnsanewEnumerator.

Exampleto_three=Enumerator.newdo|y|

3.timesdo|x|

y<<x

end

end

to_three_with_string=to_three.with_object("foo")

to_three_with_string.eachdo|x,string|

puts"#{string}:#{x}"

end

#=>foo:0

#=>foo:1

#=>foo:2

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

each_with_object(obj){|(*args),obj|...}each_with_object(obj)with_object(obj){|(*args),obj|...}with_object(obj)

Page 216: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEnumerator::GeneratorLazy

InFilesenumerator.c

ParentObject

IncludedModulesEnumerable

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 217: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEnumerator::LazyLazy

InFilesenumerator.c

ParentEnumerator

PublicClassMethods

CreatesanewLazyenumerator.Whentheenumeratorisactuallyenumerated(e.g.bycallingforce),objwillbeenumeratedandeachvaluepassedtothegivenblock.Theblockcanyieldvaluesbackusingyielder.Forexample,tocreateamethodfilter_mapinbothlazyandnon-lazyfashions:

moduleEnumerable

deffilter_map(&block)

map(&block).compact

end

end

classEnumerator::Lazy

deffilter_map

Lazy.new(self)do|yielder,*values|

result=yield*values

yielder<<resultifresult

new(obj,size=nil){|yielder,*values|...}

Page 218: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

end

end

(1..Float::INFINITY).lazy.filter_map{|i|i*iifi.even?

#=>[4,16,36,64,100]

PublicInstanceMethods

Returnsanewlazyenumeratorwiththeconcatenatedresultsofrunningblockonceforeveryelementinlazy.

["foo","bar"].lazy.flat_map{|i|i.each_char.lazy}.force

#=>["f","o","o","b","a","r"]

Avaluexreturnedbyblockisdecomposedifeitherofthefollowingconditionsistrue:

a)<i>x</i>respondstobotheachandforce,whichmeansthat

<i>x</i>isalazyenumerator.

b)<i>x</i>isanarrayorrespondstoto_ary.

Otherwise,xiscontainedas-isinthereturnvalue.

[{a:1},{b:2}].lazy.flat_map{|i|i}.force

#=>[{:a=>1},{:b=>2}]

chunk(*args)

collect()

collect_concat{|obj|block}→a_lazy_enumeratorflat_map{|obj|block}→a_lazy_enumerator

Page 219: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SimilartoKernel#to_enum,exceptitreturnsalazyenumerator.ThismakesiteasytodefineEnumerablemethodsthatwillnaturallyremainlazyifcalledfromalazyenumerator.

Forexample,continuingfromtheexampleinKernel#to_enum:

#SeeKernel#to_enumforthedefinitionofrepeat

r=1..Float::INFINITY

r.repeat(2).first(5)#=>[1,1,2,2,3]

r.repeat(2).class#=>Enumerator

r.repeat(2).map{|n|n**2}.first(5)#=>endlessloop!

#worksnaturallyonlazyenumerator:

r.lazy.repeat(2).class#=>Enumerator::Lazy

r.lazy.repeat(2).map{|n|n**2}.first(5)#=>[1,1,4,4,9]

drop(p1)

drop_while()

to_enum(method=:each,*args)→lazy_enumenum_for(method=:each,*args)→lazy_enumto_enum(method=:each,*args){|*args|block}→lazy_enumenum_for(method=:each,*args){|*args|block}→lazy_enum

find_all()

collect_concat{|obj|block}→a_lazy_enumeratorflat_map{|obj|block}→a_lazy_enumerator

Page 220: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanewlazyenumeratorwiththeconcatenatedresultsofrunningblockonceforeveryelementinlazy.

["foo","bar"].lazy.flat_map{|i|i.each_char.lazy}.force

#=>["f","o","o","b","a","r"]

Avaluexreturnedbyblockisdecomposedifeitherofthefollowingconditionsistrue:

a)<i>x</i>respondstobotheachandforce,whichmeansthat

<i>x</i>isalazyenumerator.

b)<i>x</i>isanarrayorrespondstoto_ary.

Otherwise,xiscontainedas-isinthereturnvalue.

[{a:1},{b:2}].lazy.flat_map{|i|i}.force

#=>[{:a=>1},{:b=>2}]

grep(p1)

lazy()

map()

reject()

select()

slice_after(*args)

slice_before(*args)

slice_when(*args)

Page 221: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SimilartoKernel#to_enum,exceptitreturnsalazyenumerator.ThismakesiteasytodefineEnumerablemethodsthatwillnaturallyremainlazyifcalledfromalazyenumerator.

Forexample,continuingfromtheexampleinKernel#to_enum:

#SeeKernel#to_enumforthedefinitionofrepeat

r=1..Float::INFINITY

r.repeat(2).first(5)#=>[1,1,2,2,3]

r.repeat(2).class#=>Enumerator

r.repeat(2).map{|n|n**2}.first(5)#=>endlessloop!

#worksnaturallyonlazyenumerator:

r.lazy.repeat(2).class#=>Enumerator::Lazy

r.lazy.repeat(2).map{|n|n**2}.first(5)#=>[1,1,4,4,9]

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

take(p1)

take_while()

to_enum(method=:each,*args)→lazy_enumenum_for(method=:each,*args)→lazy_enumto_enum(method=:each,*args){|*args|block}→lazy_enumenum_for(method=:each,*args){|*args|block}→lazy_enum

zip(*args)

Page 222: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classEnumerator::YielderLazy

InFilesenumerator.c

ParentObject

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 223: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleErrnoRubyexceptionobjectsaresubclassesofException.However,operatingsystemstypicallyreporterrorsusingplainintegers.ModuleErrnoiscreateddynamicallytomaptheseoperatingsystemerrorstoRubyclasses,witheacherrornumbergeneratingitsownsubclassofSystemCallError.AsthesubclassiscreatedinmoduleErrno,itsnamewillstartErrno::.

ThenamesoftheErrno::classesdependontheenvironmentinwhichRubyruns.OnatypicalUnixorWindowsplatform,thereareErrnoclassessuchasErrno::EACCES,Errno::EAGAIN,Errno::EINTR,andsoon.

TheintegeroperatingsystemerrornumbercorrespondingtoaparticularerrorisavailableastheclassconstantErrno::error::Errno.

Errno::EACCES::Errno#=>13

Errno::EAGAIN::Errno#=>11

Errno::EINTR::Errno#=>4

ThefulllistofoperatingsystemerrorsonyourparticularplatformareavailableastheconstantsofErrno.

Errno.constants#=>:E2BIG,:EACCES,:EADDRINUSE,:EADDRNOTAVAIL,...

Page 224: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

InFileserror.c

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 225: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classExceptionDescendantsofclassExceptionareusedtocommunicatebetweenKernel#raiseandrescuestatementsinbegin...endblocks.Exceptionobjectscarryinformationabouttheexception–itstype(theexception'sclassname),anoptionaldescriptivestring,andoptionaltracebackinformation.ExceptionsubclassesmayaddadditionalinformationlikeNameError#name.

ProgramsmaymakesubclassesofException,typicallyofStandardErrororRuntimeError,toprovidecustomclassesandaddadditionalinformation.Seethesubclasslistbelowfordefaultsforraiseandrescue.

Whenanexceptionhasbeenraisedbutnotyethandled(inrescue,ensure,at_exitandENDblocks)theglobalvariable$!willcontainthecurrentexceptionand$@containsthecurrentexception'sbacktrace.

ItisrecommendedthatalibraryshouldhaveonesubclassofStandardErrororRuntimeErrorandhavespecificexceptiontypesinheritfromit.Thisallowstheusertorescueagenericexceptiontypetocatchallexceptionsthelibrarymayraiseeveniffutureversionsofthelibraryaddnewexceptionsubclasses.

Page 226: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Forexample:

classMyLibrary

classError<RuntimeError

end

classWidgetError<Error

end

classFrobError<Error

end

end

TohandlebothWidgetErrorandFrobErrorthelibraryusercanrescueMyLibrary::Error.

Thebuilt-insubclassesofExceptionare:

NoMemoryErrorScriptError

LoadErrorNotImplementedErrorSyntaxError

SecurityErrorSignalException

InterruptStandardError–defaultforrescue

ArgumentErrorUncaughtThrowError

EncodingErrorFiberErrorIOError

Page 227: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

EOFErrorIndexError

KeyErrorStopIteration

LocalJumpErrorNameError

NoMethodErrorRangeError

FloatDomainErrorRegexpErrorRuntimeError–defaultforraiseSystemCallError

Errno::*ThreadErrorTypeErrorZeroDivisionError

SystemExitSystemStackErrorfatal–impossibletorescue

InFileserror.c

ParentObject

PublicClassMethods

Page 228: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Withnoargument,oriftheargumentisthesameasthereceiver,returnthereceiver.Otherwise,createanewexceptionobjectofthesameclassasthereceiver,butwithamessageequaltostring.to_str.

ConstructanewExceptionobject,optionallypassinginamessage.

PublicInstanceMethods

Equality—IfobjisnotanException,returnsfalse.Otherwise,returnstrueifexcandobjsharesameclass,messages,andbacktrace.

Returnsanybacktraceassociatedwiththeexception.Thebacktraceisanarrayofstrings,eachcontainingeither“filename:lineNo:in`method'''or“filename:lineNo.''

defa

raise"boom"

end

defb

a()

end

begin

b()

rescue=>detail

exception(string)→an_exceptionorexc

new(msg=nil)→exception

exc==obj→trueorfalse

backtrace→array

Page 229: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

printdetail.backtrace.join("\n")

end

produces:

prog.rb:2:in`a'

prog.rb:6:in`b'

prog.rb:10

Returnsanybacktraceassociatedwiththeexception.Thismethodissimilarto#backtrace,butthebacktraceisanarrayof

Thread::Backtrace::Location.

Now,thismethodisnotaffectedby#set_backtrace.

Returnsthepreviousexception($!)atthetimethisexceptionwasraised.Thisisusefulforwrappingexceptionsandretainingtheoriginalexceptioninformation.

Withnoargument,oriftheargumentisthesameasthereceiver,returnthereceiver.Otherwise,createanewexceptionobjectofthesameclassasthereceiver,butwithamessageequaltostring.to_str.

Returnthisexception'sclassnameandmessage

backtrace_locations→array

cause→an_exceptionornil

exception(string)→an_exceptionorexc

inspect→string

message→string

Page 230: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheresultofinvokingexception.to_s.Normallythisreturnstheexception'smessageorname.Bysupplyingato_strmethod,exceptionsareagreeingtobeusedwhereStringsareexpected.

Setsthebacktraceinformationassociatedwithexc.ThebacktracemustbeanarrayofStringobjectsorasingleStringintheformatdescribedin#backtrace.

Returnsexception'smessage(orthenameoftheexceptionifnomessageisset).

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

set_backtrace(backtrace)→array

to_s→string

Page 231: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classFalseClassTheglobalvaluefalseistheonlyinstanceofclassFalseClassandrepresentsalogicallyfalsevalueinbooleanexpressions.Theclassprovidesoperatorsallowingfalsetoparticipatecorrectlyinlogicalexpressions.

InFilesobject.c

ParentObject

PublicInstanceMethods

And—Returnsfalse.objisalwaysevaluatedasitistheargumenttoamethodcall—thereisnoshort-circuitevaluationinthiscase.

ExclusiveOr—Ifobjisnilorfalse,returnsfalse;otherwise,returnstrue.

false&obj→falsenil&obj→false

false^obj→trueorfalsenil^obj→trueorfalse

Page 232: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Aliasfor:to_s

'nufsaid…

Alsoaliasedas:inspect

Or—Returnsfalseifobjisnilorfalse;trueotherwise.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

inspect()

to_s→"false"

false|obj→trueorfalsenil|obj→trueorfalse

Page 233: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classFiberFibersareprimitivesforimplementinglightweightcooperativeconcurrencyinRuby.Basicallytheyareameansofcreatingcodeblocksthatcanbepausedandresumed,muchlikethreads.ThemaindifferenceisthattheyareneverpreemptedandthattheschedulingmustbedonebytheprogrammerandnottheVM.

Asopposedtootherstacklesslightweightconcurrencymodels,eachfibercomeswithasmall4KBstack.Thisenablesthefibertobepausedfromdeeplynestedfunctioncallswithinthefiberblock.

Whenafiberiscreateditwillnotrunautomatically.RatheritmustbebeexplicitlyaskedtorunusingtheFiber#resumemethod.ThecoderunninginsidethefibercangiveupcontrolbycallingFiber.yieldinwhichcaseityieldscontrolbacktocaller(thecalleroftheFiber#resume).

UponyieldingorterminationtheFiberreturnsthevalueofthelastexecutedexpression

Forinstance:

fiber=Fiber.newdo

Fiber.yield1

2

Page 234: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

putsfiber.resume

putsfiber.resume

putsfiber.resume

produces

1

2

FiberError:deadfibercalled

TheFiber#resumemethodacceptsanarbitrarynumberofparameters,ifitisthefirstcalltoresumethentheywillbepassedasblockarguments.OtherwisetheywillbethereturnvalueofthecalltoFiber.yield

Example:

fiber=Fiber.newdo|first|

second=Fiber.yieldfirst+2

end

putsfiber.resume10

putsfiber.resume14

putsfiber.resume18

produces

12

14

FiberError:deadfibercalled

Page 235: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

InFilescont.c

ParentObject

PublicClassMethods

Returnsthecurrentfiber.Youneedtorequire'fiber'beforeusingthismethod.Ifyouarenotrunninginthecontextofafiberthismethodwillreturntherootfiber.

Yieldscontrolbacktothecontextthatresumedthefiber,passingalonganyargumentsthatwerepassedtoit.Thefiberwillresumeprocessingatthispointwhenresumeiscallednext.AnyargumentspassedtothenextresumewillbethevaluethatthisFiber.yieldexpressionevaluatesto.

PublicInstanceMethods

Returnstrueifthefibercanstillberesumed(ortransferredto).Afterfinishingexecutionofthefiberblockthismethodwillalwaysreturnfalse.Youneedtorequire'fiber'beforeusingthismethod.

current()→fiber

yield(args,...)→obj

alive?→trueorfalse

Page 236: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ResumesthefiberfromthepointatwhichthelastFiber.yieldwascalled,orstartsrunningitifitisthefirstcalltoresume.ArgumentspassedtoresumewillbethevalueoftheFiber.yieldexpressionorwillbepassedasblockparameterstothefiber'sblockifthisisthefirstresume.

Alternatively,whenresumeiscalleditevaluatestotheargumentspassedtothenextFiber.yieldstatementinsidethefiber'sblockortotheblockvalueifitrunstocompletionwithoutanyFiber.yield

Transfercontroltoanotherfiber,resumingitfromwhereitlaststoppedorstartingitifitwasnotresumedbefore.ThecallingfiberwillbesuspendedmuchlikeinacalltoFiber.yield.Youneedtorequire'fiber'beforeusingthismethod.

Thefiberwhichreceivesthetransfercallistreatsitmuchlikearesumecall.Argumentspassedtotransferaretreatedlikethosepassedtoresume.

Youcannotresumeafiberthattransferredcontroltoanotherone.Thiswillcauseadoubleresumeerror.Youneedtotransfercontrolbacktothisfiberbeforeitcanyieldandresume.

Example:

fiber1=Fiber.newdo

puts"InFiber1"

Fiber.yield

end

fiber2=Fiber.newdo

puts"InFiber2"

resume(args,...)→obj

transfer(args,...)→obj

Page 237: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

fiber1.transfer

puts"Neverseethismessage"

end

fiber3=Fiber.newdo

puts"InFiber3"

end

fiber2.resume

fiber3.resume

produces

Infiber2

Infiber1

Infiber3

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 238: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classFiberErrorRaisedwhenaninvalidoperationisattemptedonaFiber,inparticularwhenattemptingtocall/resumeadeadfiber,attemptingtoyieldfromtherootfiber,orcallingafiberacrossthreads.

fiber=Fiber.new{}

fiber.resume#=>nil

fiber.resume#=>FiberError:deadfibercalled

InFilescont.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 239: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classFileAFileisanabstractionofanyfileobjectaccessiblebytheprogramandiscloselyassociatedwithclassIOFileincludesthemethodsofmoduleFileTestasclassmethods,allowingyoutowrite(forexample)File.exist?("foo").

InthedescriptionofFilemethods,permissionbitsareaplatform-specificsetofbitsthatindicatepermissionsofafile.OnUnix-basedsystems,permissionsareviewedasasetofthreeoctets,fortheowner,thegroup,andtherestoftheworld.Foreachoftheseentities,permissionsmaybesettoread,write,orexecutethefile:

Thepermissionbits0644(inoctal)wouldthusbeinterpretedasread/writeforowner,andread-onlyforgroupandother.Higher-orderbitsmayalsobeusedtoindicatethetypeoffile(plain,directory,pipe,socket,andsoon)andvariousotherspecialfeatures.Ifthepermissionsareforadirectory,themeaningoftheexecutebitchanges;whensetthedirectorycanbesearched.

Onnon-Posixoperatingsystems,theremaybeonlytheabilitytomakeafileread-onlyorread-write.Inthiscase,theremainingpermissionbits

Page 240: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

willbesynthesizedtoresembletypicalvalues.Forinstance,onWindowsNTthedefaultpermissionbitsare0644,whichmeansread/writeforowner,read-onlyforallothers.Theonlychangethatcanbemadeistomakethefileread-only,whichisreportedas0444.

VariousconstantsforthemethodsinFilecanbefoundinFile::Constants.

InFilesdir.cfile.cio.c

ParentIO

Constants

ALT_SEPARATOR

platformspecificalternativeseparator

PATH_SEPARATOR

pathlistseparator

SEPARATOR

separatesdirectorypartsinpath

Page 241: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Separator

separatesdirectorypartsinpath

PublicClassMethods

Convertsapathnametoanabsolutepathname.Relativepathsarereferencedfromthecurrentworkingdirectoryoftheprocessunlessdir_stringisgiven,inwhichcaseitwillbeusedasthestartingpoint.Ifthegivenpathnamestartswitha“~''itisNOTexpanded,itistreatedasanormaldirectoryname.

File.absolute_path("~oracle/bin")#=>"<relative_path>/~oracle/bin"

ReturnsthelastaccesstimeforthenamedfileasaTimeobject).

file_namecanbeanIOobject.

File.atime("testfile")#=>WedApr0908:51:48CDT2003

Returnsthelastcomponentofthefilenamegiveninfile_name,whichcanbeformedusingbothFile::SEPARATORandFile::ALT_SEPARATORastheseparatorwhenFile::ALT_SEPARATORisnotnil.Ifsuffixisgivenandpresentattheendoffile_name,itisremoved.Ifsuffixis“.*”,anyextensionwillbe

absolute_path(file_name[,dir_string])→abs_file_name

atime(file_name)→time

basename(file_name[,suffix])→base_name

Page 242: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

removed.

File.basename("/home/gumby/work/ruby.rb")#=>"ruby.rb"

File.basename("/home/gumby/work/ruby.rb",".rb")#=>"ruby"

File.basename("/home/gumby/work/ruby.rb",".*")#=>"ruby"

Returnsthebirthtimeforthenamedfile.

file_namecanbeanIOobject.

NotethatonWindows(NTFS),returnscreationtime(birthtime).

File.birthtime("testfile")#=>WedApr0908:53:13CDT2003

Returnstrueifthenamedfileisablockdevice.

file_namecanbeanIOobject.

Returnstrueifthenamedfileisacharacterdevice.

file_namecanbeanIOobject.

Changespermissionbitsonthenamedfile(s)tothebitpatternrepresentedbymode_int.Actualeffectsareoperatingsystemdependent(seethebeginningofthissection).OnUnixsystems,seechmod(2)fordetails.Returnsthenumberoffilesprocessed.

File.chmod(0644,"testfile","out")#=>2

birthtime(file_name)→time

blockdev?(file_name)→trueorfalse

chardev?(file_name)→trueorfalse

chmod(mode_int,file_name,...)→integer

Page 243: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Changestheownerandgroupofthenamedfile(s)tothegivennumericownerandgroupid's.Onlyaprocesswithsuperuserprivilegesmaychangetheownerofafile.Thecurrentownerofafilemaychangethefile'sgrouptoanygrouptowhichtheownerbelongs.Anilor-1ownerorgroupidisignored.Returnsthenumberoffilesprocessed.

File.chown(nil,100,"testfile")

Returnsthechangetimeforthenamedfile(thetimeatwhichdirectoryinformationaboutthefilewaschanged,notthefileitself).

file_namecanbeanIOobject.

NotethatonWindows(NTFS),returnscreationtime(birthtime).

File.ctime("testfile")#=>WedApr0908:53:13CDT2003

Deletesthenamedfiles,returningthenumberofnamespassedasarguments.Raisesanexceptiononanyerror.SeealsoDir::rmdir.

Returnstrueifthenamedfileisadirectory,orasymlinkthatpointsatadirectory,andfalseotherwise.

chown(owner_int,group_int,file_name,...)→integer

ctime(file_name)→time

delete(file_name,...)→integerunlink(file_name,...)→integer

directory?(file_name)→trueorfalse

Page 244: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

file_namecanbeanIOobject.

File.directory?(".")

Returnsallcomponentsofthefilenamegiveninfile_nameexceptthelastone.ThefilenamecanbeformedusingbothFile::SEPARATORandFile::ALT_SEPARATORastheseparatorwhenFile::ALT_SEPARATORisnotnil.

File.dirname("/home/gumby/work/ruby.rb")#=>"/home/gumby/work"

Returnstrueifthenamedfileisexecutablebytheeffectiveuseridofthisprocess.

Returnstrueifthenamedfileisexecutablebytherealuseridofthisprocess.

Returntrueifthenamedfileexists.

file_namecanbeanIOobject.

“fileexists”meansthatstat()orfstat()systemcallissuccessful.

Deprecatedmethod.Don'tuse.

dirname(file_name)→dir_name

executable?(file_name)→trueorfalse

executable_real?(file_name)→trueorfalse

exist?(file_name)→trueorfalse

exists?(file_name)→trueorfalse

Page 245: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Convertsapathnametoanabsolutepathname.Relativepathsarereferencedfromthecurrentworkingdirectoryoftheprocessunlessdir_stringisgiven,inwhichcaseitwillbeusedasthestartingpoint.Thegivenpathnamemaystartwitha“~'',whichexpandstotheprocessowner'shomedirectory(theenvironmentvariableHOMEmustbesetcorrectly).“~user''expandstothenameduser'shomedirectory.

File.expand_path("~oracle/bin")#=>"/home/oracle/bin"

Asimpleexampleofusingdir_stringisasfollows.

File.expand_path("ruby","/usr/bin")#=>"/usr/bin/ruby"

Amorecomplexexamplewhichalsoresolvesparentdirectoryisasfollows.Supposeweareinbin/mygemandwanttheabsolutepathoflib/mygem.rb.

File.expand_path("../../lib/mygem.rb",__FILE__)

#=>".../path/to/project/lib/mygem.rb"

Sofirstitresolvestheparentof__FILE__,thatisbin/,thengototheparent,therootoftheprojectandappendslib/mygem.rb.

Returnstheextension(theportionoffilenameinpathstartingfromthelastperiod).

Ifpathisadotfile,orstartswithaperiod,thenthestartingdotisnotdealtwiththestartoftheextension.

Anemptystringwillalsobereturnedwhentheperiod

expand_path(file_name[,dir_string])→abs_file_name

extname(path)→string

Page 246: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

isthelastcharacterinpath.

File.extname("test.rb")#=>".rb"

File.extname("a/b/d/test.rb")#=>".rb"

File.extname("foo.")#=>""

File.extname("test")#=>""

File.extname(".profile")#=>""

File.extname(".profile.sh")#=>".sh"

Returnstrueifthenamedfileexistsandisaregularfile.

filecanbeanIOobject.

Ifthefileargumentisasymboliclink,itwillresolvethesymboliclinkandusethefilereferencedbythelink.

Returnstrueifpathmatchesagainstpattern.Thepatternisnotaregularexpression;insteaditfollowsrulessimilartoshellfilenameglobbing.Itmaycontainthefollowingmetacharacters:*

Matchesanyfile.Canberestrictedbyothervaluesintheglob.Equivalentto/.*/xinregexp.*

Matchesallfilesregularfiles

c*

Matchesallfilesbeginningwithc

*c

file?(file)→trueorfalse

fnmatch(pattern,path,[flags])→(trueorfalse)fnmatch?(pattern,path,[flags])→(trueorfalse)

Page 247: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Matchesallfilesendingwithc

*c*

Matchesallfilesthathavecinthem(includingatthebeginningorend).

Tomatchhiddenfiles(thatstartwitha.settheFile::FNM_DOTMATCHflag.

**

Matchesdirectoriesrecursivelyorfilesexpansively.

?

Matchesanyonecharacter.Equivalentto/.{1}/inregexp.

[set]

Matchesanyonecharacterinset.BehavesexactlylikecharactersetsinRegexp,includingsetnegation([^a-z]).

\

Escapesthenextmetacharacter.

{a,b}

MatchespatternaandpatternbifFile::FNM_EXTGLOBflagisenabled.BehaveslikeaRegexpunion((?:a|b)).

flagsisabitwiseORoftheFNM_XXXconstants.ThesameglobpatternandflagsareusedbyDir.glob.

Examples:

File.fnmatch('cat','cat')#=>true#matchentirestring

File.fnmatch('cat','category')#=>false#onlymatchpartialstring

File.fnmatch('c{at,ub}s','cats')#=>false#{}isn'tsupportedbydefault

File.fnmatch('c{at,ub}s','cats',File::FNM_EXTGLOB)#=>true#{}issupportedonFNM_EXTGLOB

File.fnmatch('c?t','cat')#=>true#'?'matchonly1character

File.fnmatch('c??t','cat')#=>false#ditto

File.fnmatch('c*','cats')#=>true#'*'match0ormorecharacters

Page 248: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

File.fnmatch('c*t','c/a/b/t')#=>true#ditto

File.fnmatch('ca[a-z]','cat')#=>true#inclusivebracketexpression

File.fnmatch('ca[^t]','cat')#=>false#exclusivebracketexpression('^'or'!')

File.fnmatch('cat','CAT')#=>false#casesensitive

File.fnmatch('cat','CAT',File::FNM_CASEFOLD)#=>true#caseinsensitive

File.fnmatch('?','/',File::FNM_PATHNAME)#=>false#wildcarddoesn'tmatch'/'onFNM_PATHNAME

File.fnmatch('*','/',File::FNM_PATHNAME)#=>false#ditto

File.fnmatch('[/]','/',File::FNM_PATHNAME)#=>false#ditto

File.fnmatch('\?','?')#=>true#escapedwildcardbecomesordinary

File.fnmatch('\a','a')#=>true#escapedordinaryremainsordinary

File.fnmatch('\a','\a',File::FNM_NOESCAPE)#=>true#FNM_NOESCAPEmakes'\'ordinary

File.fnmatch('[\?]','?')#=>true#canescapeinsidebracketexpression

File.fnmatch('*','.profile')#=>false#wildcarddoesn'tmatchleading

File.fnmatch('*','.profile',File::FNM_DOTMATCH)#=>true#periodbydefault.

File.fnmatch('.*','.profile')#=>true

rbfiles='**''/''*.rb'#youdon'thavetodolikethis.justwriteinsinglestring.

File.fnmatch(rbfiles,'main.rb')#=>false

File.fnmatch(rbfiles,'./main.rb')#=>false

File.fnmatch(rbfiles,'lib/song.rb')#=>true

File.fnmatch('**.rb','main.rb')#=>true

File.fnmatch('**.rb','./main.rb')#=>false

File.fnmatch('**.rb','lib/song.rb')#=>true

File.fnmatch('*','dave/.profile')

pattern='*''/''*'

File.fnmatch(pattern,'dave/.profile',File::FNM_PATHNAME

File.fnmatch(pattern,'dave/.profile',File::FNM_PATHNAME

pattern='**''/''foo'

File.fnmatch(pattern,'a/b/c/foo',File::FNM_PATHNAME)

File.fnmatch(pattern,'/a/b/c/foo',File::FNM_PATHNAME

File.fnmatch(pattern,'c:/a/b/c/foo',File::FNM_PATHNAME

File.fnmatch(pattern,'a/.b/c/foo',File::FNM_PATHNAME

File.fnmatch(pattern,'a/.b/c/foo',File::FNM_PATHNAME

fnmatch(pattern,path,[flags])→(trueorfalse)fnmatch?(pattern,path,[flags])→(trueor

Page 249: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifpathmatchesagainstpattern.Thepatternisnotaregularexpression;insteaditfollowsrulessimilartoshellfilenameglobbing.Itmaycontainthefollowingmetacharacters:*

Matchesanyfile.Canberestrictedbyothervaluesintheglob.Equivalentto/.*/xinregexp.*

Matchesallfilesregularfiles

c*

Matchesallfilesbeginningwithc

*c

Matchesallfilesendingwithc

*c*

Matchesallfilesthathavecinthem(includingatthebeginningorend).

Tomatchhiddenfiles(thatstartwitha.settheFile::FNM_DOTMATCHflag.

**

Matchesdirectoriesrecursivelyorfilesexpansively.

?

Matchesanyonecharacter.Equivalentto/.{1}/inregexp.

[set]

Matchesanyonecharacterinset.BehavesexactlylikecharactersetsinRegexp,includingsetnegation([^a-z]).

\

Escapesthenextmetacharacter.

{a,b}

false)

Page 250: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

MatchespatternaandpatternbifFile::FNM_EXTGLOBflagisenabled.BehaveslikeaRegexpunion((?:a|b)).

flagsisabitwiseORoftheFNM_XXXconstants.ThesameglobpatternandflagsareusedbyDir.glob.

Examples:

File.fnmatch('cat','cat')#=>true#matchentirestring

File.fnmatch('cat','category')#=>false#onlymatchpartialstring

File.fnmatch('c{at,ub}s','cats')#=>false#{}isn'tsupportedbydefault

File.fnmatch('c{at,ub}s','cats',File::FNM_EXTGLOB)#=>true#{}issupportedonFNM_EXTGLOB

File.fnmatch('c?t','cat')#=>true#'?'matchonly1character

File.fnmatch('c??t','cat')#=>false#ditto

File.fnmatch('c*','cats')#=>true#'*'match0ormorecharacters

File.fnmatch('c*t','c/a/b/t')#=>true#ditto

File.fnmatch('ca[a-z]','cat')#=>true#inclusivebracketexpression

File.fnmatch('ca[^t]','cat')#=>false#exclusivebracketexpression('^'or'!')

File.fnmatch('cat','CAT')#=>false#casesensitive

File.fnmatch('cat','CAT',File::FNM_CASEFOLD)#=>true#caseinsensitive

File.fnmatch('?','/',File::FNM_PATHNAME)#=>false#wildcarddoesn'tmatch'/'onFNM_PATHNAME

File.fnmatch('*','/',File::FNM_PATHNAME)#=>false#ditto

File.fnmatch('[/]','/',File::FNM_PATHNAME)#=>false#ditto

File.fnmatch('\?','?')#=>true#escapedwildcardbecomesordinary

File.fnmatch('\a','a')#=>true#escapedordinaryremainsordinary

File.fnmatch('\a','\a',File::FNM_NOESCAPE)#=>true#FNM_NOESCAPEmakes'\'ordinary

File.fnmatch('[\?]','?')#=>true#canescapeinsidebracketexpression

File.fnmatch('*','.profile')#=>false#wildcarddoesn'tmatchleading

File.fnmatch('*','.profile',File::FNM_DOTMATCH)#=>true#periodbydefault.

File.fnmatch('.*','.profile')#=>true

rbfiles='**''/''*.rb'#youdon'thavetodolikethis.justwriteinsinglestring.

File.fnmatch(rbfiles,'main.rb')#=>false

File.fnmatch(rbfiles,'./main.rb')#=>false

File.fnmatch(rbfiles,'lib/song.rb')#=>true

File.fnmatch('**.rb','main.rb')#=>true

File.fnmatch('**.rb','./main.rb')#=>false

File.fnmatch('**.rb','lib/song.rb')#=>true

File.fnmatch('*','dave/.profile')

Page 251: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

pattern='*''/''*'

File.fnmatch(pattern,'dave/.profile',File::FNM_PATHNAME

File.fnmatch(pattern,'dave/.profile',File::FNM_PATHNAME

pattern='**''/''foo'

File.fnmatch(pattern,'a/b/c/foo',File::FNM_PATHNAME)

File.fnmatch(pattern,'/a/b/c/foo',File::FNM_PATHNAME

File.fnmatch(pattern,'c:/a/b/c/foo',File::FNM_PATHNAME

File.fnmatch(pattern,'a/.b/c/foo',File::FNM_PATHNAME

File.fnmatch(pattern,'a/.b/c/foo',File::FNM_PATHNAME

Identifiesthetypeofthenamedfile;thereturnstringisoneof“file'',“directory'',“characterSpecial'',“blockSpecial'',“fifo'',“link'',“socket'',or“unknown''.

File.ftype("testfile")#=>"file"

File.ftype("/dev/tty")#=>"characterSpecial"

File.ftype("/tmp/.X11-unix/X0")#=>"socket"

Returnstrueifthenamedfileexistsandtheeffectivegroupidofthecallingprocessistheownerofthefile.ReturnsfalseonWindows.

file_namecanbeanIOobject.

Returnstrueifthenamedfilesareidentical.

file_1andfile_2canbeanIOobject.

open("a","w"){}

pFile.identical?("a","a")#=>true

pFile.identical?("a","./a")#=>true

File.link("a","b")

ftype(file_name)→string

grpowned?(file_name)→trueorfalse

identical?(file_1,file_2)→trueorfalse

Page 252: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

pFile.identical?("a","b")#=>true

File.symlink("a","c")

pFile.identical?("a","c")#=>true

open("d","w"){}

pFile.identical?("a","d")#=>false

ReturnsanewstringformedbyjoiningthestringsusingFile::SEPARATOR.

File.join("usr","mail","gumby")#=>"usr/mail/gumby"

EquivalenttoFile::chmod,butdoesnotfollowsymboliclinks(soitwillchangethepermissionsassociatedwiththelink,notthefilereferencedbythelink).Oftennotavailable.

EquivalenttoFile::chown,butdoesnotfollowsymboliclinks(soitwillchangetheownerassociatedwiththelink,notthefilereferencedbythelink).Oftennotavailable.Returnsnumberoffilesintheargumentlist.

Createsanewnameforanexistingfileusingahardlink.Willnotoverwritenew_nameifitalreadyexists(raisingasubclassofSystemCallError).Notavailableonallplatforms.

File.link("testfile",".testfile")#=>0

IO.readlines(".testfile")[0]#=>"Thisislineone\n"

join(string,...)→string

lchmod(mode_int,file_name,...)→integer

lchown(owner_int,group_int,file_name,..)→integer

link(old_name,new_name)→0

Page 253: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SameasFile::stat,butdoesnotfollowthelastsymboliclink.Instead,reportsonthelinkitself.

File.symlink("testfile","link2test")#=>0

File.stat("testfile").size#=>66

File.lstat("link2test").size#=>8

File.stat("link2test").size#=>66

ReturnsthemodificationtimeforthenamedfileasaTimeobject.

file_namecanbeanIOobject.

File.mtime("testfile")#=>TueApr0812:58:04CDT2003

OpensthefilenamedbyfilenameaccordingtothegivenmodeandreturnsanewFileobject.

SeeIO.newforadescriptionofmodeandopt.

Ifafileisbeingcreated,permissionbitsmaybegiveninperm.Thesemodeandpermissionbitsareplatformdependent;onUnixsystems,seeopen(2)andchmod(2)manpagesfordetails.

Examplesf=File.new("testfile","r")

f=File.new("newfile","w+")

f=File.new("newfile",File::CREAT|File::TRUNC|File::RDWR,0644)

lstat(file_name)→stat

mtime(file_name)→time

new(filename,mode="r"[,opt])→filenew(filename[,mode[,perm]][,opt])→file

Page 254: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Withnoassociatedblock,File.openisasynonymfor::new.Iftheoptionalcodeblockisgiven,itwillbepassedtheopenedfileasanargumentandtheFileobjectwillautomaticallybeclosedwhentheblockterminates.ThevalueoftheblockwillbereturnedfromFile.open.

Ifafileisbeingcreated,itsinitialpermissionsmaybesetusingthepermparameter.See::newforfurtherdiscussion.

SeeIO.newforadescriptionofthemodeandoptparameters.

Returnstrueifthenamedfileexistsandtheeffectiveusedidofthecallingprocessistheownerofthefile.

file_namecanbeanIOobject.

Returnsthestringrepresentationofthepath

File.path("/dev/null")#=>"/dev/null"

File.path(Pathname.new("/tmp"))#=>"/tmp"

open(filename,mode="r"[,opt])→fileopen(filename[,mode[,perm]][,opt])→fileopen(filename,mode="r"[,opt]){|file|block}→objopen(filename[,mode[,perm]][,opt]){|file|block}→obj

owned?(file_name)→trueorfalse

path(path)→string

pipe?(file_name)→trueorfalse

Page 255: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthenamedfileisapipe.

file_namecanbeanIOobject.

Returnstrueifthenamedfileisreadablebytheeffectiveuseridofthisprocess.

Returnstrueifthenamedfileisreadablebytherealuseridofthisprocess.

Returnsthenameofthefilereferencedbythegivenlink.Notavailableonallplatforms.

File.symlink("testfile","link2test")#=>0

File.readlink("link2test")#=>"testfile"

Returnsthereal(absolute)pathnameofpathnameintheactualfilesystem.Therealpathnamedoesn'tcontainsymlinksoruselessdots.

Ifdir_stringisgiven,itisusedasabasedirectoryforinterpretingrelativepathnameinsteadofthecurrentdirectory.

Thelastcomponentoftherealpathnamecanbenonexistent.

readable?(file_name)→trueorfalse

readable_real?(file_name)→trueorfalse

readlink(link_name)→file_name

realdirpath(pathname[,dir_string])→real_pathname

realpath(pathname[,dir_string])→

Page 256: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthereal(absolute)pathnameofpathnameintheactualfilesystemnotcontainingsymlinksoruselessdots.

Ifdir_stringisgiven,itisusedasabasedirectoryforinterpretingrelativepathnameinsteadofthecurrentdirectory.

Allcomponentsofthepathnamemustexistwhenthismethodiscalled.

Renamesthegivenfiletothenewname.RaisesaSystemCallErrorifthefilecannotberenamed.

File.rename("afile","afile.bak")#=>0

Returnstrueifthenamedfilehasthesetgidbitset.

Returnstrueifthenamedfilehasthesetuidbitset.

Returnsthesizeoffile_name.

file_namecanbeanIOobject.

Returnsniliffile_namedoesn'texistorhaszerosize,thesizeofthefileotherwise.

file_namecanbeanIOobject.

real_pathname

rename(old_name,new_name)→0

setgid?(file_name)→trueorfalse

setuid?(file_name)→trueorfalse

size(file_name)→integer

size?(file_name)→Integerornil

Page 257: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthenamedfileisasocket.

file_namecanbeanIOobject.

Splitsthegivenstringintoadirectoryandafilecomponentandreturnstheminatwo-elementarray.SeealsoFile::dirnameandFile::basename.

File.split("/home/gumby/.profile")#=>["/home/gumby",".profile"]

ReturnsaFile::Statobjectforthenamedfile(seeFile::Stat).

File.stat("testfile").mtime#=>TueApr0812:58:04CDT2003

Returnstrueifthenamedfilehasthestickybitset.

Createsasymboliclinkcallednew_namefortheexistingfileold_name.RaisesaNotImplementedexceptiononplatformsthatdonotsupportsymboliclinks.

File.symlink("testfile","link2test")#=>0

socket?(file_name)→trueorfalse

split(file_name)→array

stat(file_name)→stat

sticky?(file_name)→trueorfalse

symlink(old_name,new_name)→0

symlink?(file_name)→trueorfalse

Page 258: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthenamedfileisasymboliclink.

Truncatesthefilefile_nametobeatmostintegerbyteslong.Notavailableonallplatforms.

f=File.new("out","w")

f.write("1234567890")#=>10

f.close#=>nil

File.truncate("out",5)#=>0

File.size("out")#=>5

Returnsthecurrentumaskvalueforthisprocess.Iftheoptionalargumentisgiven,settheumasktothatvalueandreturnthepreviousvalue.Umaskvaluesaresubtractedfromthedefaultpermissions,soaumaskof0222wouldmakeafileread-onlyforeveryone.

File.umask(0006)#=>18

File.umask#=>6

Deletesthenamedfiles,returningthenumberofnamespassedasarguments.Raisesanexceptiononanyerror.SeealsoDir::rmdir.

Setstheaccessandmodificationtimesofeachnamedfiletothefirsttwoarguments.Returnsthenumberoffilenamesintheargumentlist.

truncate(file_name,integer)→0

umask()→integerumask(integer)→integer

delete(file_name,...)→integerunlink(file_name,...)→integer

utime(atime,mtime,file_name,...)→integer

Page 259: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Iffile_nameisreadablebyothers,returnsanintegerrepresentingthefilepermissionbitsoffile_name.Returnsnilotherwise.Themeaningofthebitsisplatformdependent;onUnixsystems,seestat(2).

file_namecanbeanIOobject.

File.world_readable?("/etc/passwd")#=>420

m=File.world_readable?("/etc/passwd")

sprintf("%o",m)#=>"644"

Iffile_nameiswritablebyothers,returnsanintegerrepresentingthefilepermissionbitsoffile_name.Returnsnilotherwise.Themeaningofthebitsisplatformdependent;onUnixsystems,seestat(2).

file_namecanbeanIOobject.

File.world_writable?("/tmp")#=>511

m=File.world_writable?("/tmp")

sprintf("%o",m)#=>"777"

Returnstrueifthenamedfileiswritablebytheeffectiveuseridofthisprocess.

Returnstrueifthenamedfileiswritablebytherealuseridofthisprocess.

world_readable?(file_name)→fixnumornil

world_writable?(file_name)→fixnumornil

writable?(file_name)→trueorfalse

writable_real?(file_name)→trueorfalse

Page 260: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthenamedfileexistsandhasazerosize.

file_namecanbeanIOobject.

PublicInstanceMethods

Returnsthelastaccesstime(aTimeobject)

for<i>file</i>,orepochif<i>file</>hasnotbeenaccessed

File.new("testfile").atime#=>WedDec3118:00:00CST1969

Returnsthebirthtimeforfile.

NotethatonWindows(NTFS),returnscreationtime(birthtime).

File.new("testfile").birthtime#=>WedApr0908:53:14CDT2003

Changespermissionbitsonfiletothebitpatternrepresentedbymode_int.Actualeffectsareplatformdependent;onUnixsystems,seechmod(2)fordetails.Followssymboliclinks.AlsoseeFile#lchmod.

f=File.new("out","w");

f.chmod(0644)#=>0

zero?(file_name)→trueorfalse

atime→time

birthtime→time

chmod(mode_int)→0

Page 261: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Changestheownerandgroupoffiletothegivennumericownerandgroupid's.Onlyaprocesswithsuperuserprivilegesmaychangetheownerofafile.Thecurrentownerofafilemaychangethefile'sgrouptoanygrouptowhichtheownerbelongs.Anilor-1ownerorgroupidisignored.Followssymboliclinks.SeealsoFile#lchown.

File.new("testfile").chown(502,1000)

Returnsthechangetimeforfile(thatis,thetimedirectoryinformationaboutthefilewaschanged,notthefileitself).

NotethatonWindows(NTFS),returnscreationtime(birthtime).

File.new("testfile").ctime#=>WedApr0908:53:14CDT2003

Locksorunlocksafileaccordingtolocking_constant(alogicalorofthevaluesinthetablebelow).ReturnsfalseifFile::LOCK_NBisspecifiedandtheoperationwouldotherwisehaveblocked.Notavailableonallplatforms.

Lockingconstants(inclassFile):

LOCK_EX|Exclusivelock.Onlyoneprocessmayholdan

|exclusivelockforagivenfileatatime.

----------+------------------------------------------------

LOCK_NB|Don'tblockwhenlocking.Maybecombined

|withotherlockoptionsusinglogicalor.

----------+------------------------------------------------

LOCK_SH|Sharedlock.Multipleprocessesmayeachholda

chown(owner_int,group_int)→0

ctime→time

flock(locking_constant)→0orfalse

Page 262: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

|sharedlockforagivenfileatthesametime.

----------+------------------------------------------------

LOCK_UN|Unlock.

Example:

#updateacounterusingwritelock

#don'tuse"w"becauseittruncatesthefilebeforelock.

File.open("counter",File::RDWR|File::CREAT,0644){|f

f.flock(File::LOCK_EX)

value=f.read.to_i+1

f.rewind

f.write("#{value}\n")

f.flush

f.truncate(f.pos)

}

#readthecounterusingreadlock

File.open("counter","r"){|f|

f.flock(File::LOCK_SH)

pf.read

}

SameasIO#stat,butdoesnotfollowthelastsymboliclink.Instead,reportsonthelinkitself.

File.symlink("testfile","link2test")#=>0

File.stat("testfile").size#=>66

f=File.new("link2test")

f.lstat.size#=>8

f.stat.size#=>66

Returnsthemodificationtimeforfile.

File.new("testfile").mtime#=>WedApr0908:53:14CDT2003

lstat→stat

mtime→time

Page 263: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthepathnameusedtocreatefileasastring.Doesnotnormalizethename.

File.new("testfile").path#=>"testfile"

File.new("/tmp/../tmp/xxx","w").path#=>"/tmp/../tmp/xxx"

Returnsthesizeoffileinbytes.

File.new("testfile").size#=>66

Returnsthepathnameusedtocreatefileasastring.Doesnotnormalizethename.

File.new("testfile").path#=>"testfile"

File.new("/tmp/../tmp/xxx","w").path#=>"/tmp/../tmp/xxx"

Truncatesfiletoatmostintegerbytes.Thefilemustbeopenedforwriting.Notavailableonallplatforms.

f=File.new("out","w")

f.syswrite("1234567890")#=>10

f.truncate(5)#=>0

f.close()#=>nil

File.size("out")#=>5

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

path→filenameto_path→filename

size→integer

path→filenameto_path→filename

truncate(integer)→0

Page 264: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleFile::ConstantsFile::Constantsprovidesfile-relatedconstants.Allpossiblefileconstantsarelistedinthedocumentationbuttheymaynotallbepresentonyourplatform.

Iftheunderlyingplatformdoesn'tdefineaconstantthecorrespondingRubyconstantisnotdefined.

Yourplatformdocumentations(e.g.manopen(2))maydescribemoredetailedinformation.

InFilesdir.c

Constants

APPEND

appendoneachwrite

BINARY

disablelinecodeconversion

CREAT

Page 265: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

createfileifitdoesnotexist

DIRECT

TrytominimizecacheeffectsoftheI/Otoandfromthisfile.

DSYNC

anywriteoperationperformsynchronouslyexceptsomemetadata

EXCL

errorifCREATandthefileexists

LOCK_EX

exclusivelock.seeFile#flock

LOCK_NB

non-blockinglock.usedwithLOCK_SHorLOCK_EX.seeFile#flock

LOCK_SH

sharedlock.seeFile#flock

LOCK_UN

unlock.seeFile#flock

NOATIME

donotchangeatime

NOCTTY

nottomakeopenedIOthecontrollingterminaldevice

Page 266: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

NOFOLLOW

donotfollowsymlinks

NONBLOCK

donotblockonopenorfordatatobecomeavailable

NULL

Nameofthenulldevice

RDONLY

openforreadingonly

RDWR

openforreadingandwriting

RSYNC

anyreadoperationperformsynchronously.usedwithSYNCorDSYNC.

SYNC

anywriteoperationperformsynchronously

TRUNC

truncatesizeto0

WRONLY

openforwritingonly

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 267: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classFile::StatObjectsofclassFile::StatencapsulatecommonstatusinformationforFileobjects.TheinformationisrecordedatthemomenttheFile::Statobjectiscreated;changesmadetothefileafterthatpointwillnotbereflected.File::StatobjectsarereturnedbyIO#stat,File::stat,File#lstat,andFile::lstat.Manyofthesemethodsreturnplatform-specificvalues,andnotallvaluesaremeaningfulonallsystems.SeealsoKernel#test.

InFilesdir.c

ParentObject

IncludedModulesComparable

PublicClassMethods

CreateaFile::Statobjectforthegivenfilename(raisinganexceptionifthefiledoesn'texist).

File::Stat.new(file_name)→stat

Page 268: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PublicInstanceMethods

ComparesFile::Statobjectsbycomparingtheirrespectivemodificationtimes.

nilisreturnedifother_statisnotaFile::Statobject

f1=File.new("f1","w")

sleep1

f2=File.new("f2","w")

f1.stat<=>f2.stat#=>-1

ReturnsthelastaccesstimeforthisfileasanobjectofclassTime.

File.stat("testfile").atime#=>WedDec3118:00:00CST1969

Returnsthebirthtimeforstat.Iftheplatformdoesn'thavebirthtime,returnsctime.

File.write("testfile","foo")

sleep10

File.write("testfile","bar")

sleep10

File.chmod(0644,"testfile")

sleep10

File.read("testfile")

File.stat("testfile").birthtime#=>2014-02-2411:19:17+0900

File.stat("testfile").mtime#=>2014-02-2411:19:27+0900

File.stat("testfile").ctime#=>2014-02-2411:19:37+0900

File.stat("testfile").atime#=>2014-02-2411:19:47+0900

stat<=>other_stat→-1,0,1,nil

atime→time

birthtime→aTime

Page 269: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthenativefilesystem'sblocksize.Willreturnnilonplatformsthatdon'tsupportthisinformation.

File.stat("testfile").blksize#=>4096

Returnstrueifthefileisablockdevice,falseifitisn'toriftheoperatingsystemdoesn'tsupportthisfeature.

File.stat("testfile").blockdev?#=>false

File.stat("/dev/hda1").blockdev?#=>true

Returnsthenumberofnativefilesystemblocksallocatedforthisfile,orniliftheoperatingsystemdoesn'tsupportthisfeature.

File.stat("testfile").blocks#=>2

Returnstrueifthefileisacharacterdevice,falseifitisn'toriftheoperatingsystemdoesn'tsupportthisfeature.

File.stat("/dev/tty").chardev?#=>true

Returnsthechangetimeforstat(thatis,thetimedirectoryinformationaboutthefilewaschanged,notthefileitself).

blksize→integerornil

blockdev?→trueorfalse

blocks→integerornil

chardev?→trueorfalse

ctime→aTime

Page 270: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

NotethatonWindows(NTFS),returnscreationtime(birthtime).

File.stat("testfile").ctime#=>WedApr0908:53:14CDT2003

Returnsanintegerrepresentingthedeviceonwhichstatresides.

File.stat("testfile").dev#=>774

ReturnsthemajorpartofFile_Stat#devornil.

File.stat("/dev/fd1").dev_major#=>2

File.stat("/dev/tty").dev_major#=>5

ReturnstheminorpartofFile_Stat#devornil.

File.stat("/dev/fd1").dev_minor#=>1

File.stat("/dev/tty").dev_minor#=>0

Returnstrueifthenamedfileisadirectory,orasymlinkthatpointsatadirectory,andfalseotherwise.

file_namecanbeanIOobject.

File.directory?(".")

dev→fixnum

dev_major→fixnum

dev_minor→fixnum

directory?(file_name)→trueorfalse

executable?→trueorfalse

Page 271: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifstatisexecutableoriftheoperatingsystemdoesn'tdistinguishexecutablefilesfromnonexecutablefiles.Thetestsaremadeusingtheeffectiveowneroftheprocess.

File.stat("testfile").executable?#=>false

Sameasexecutable?,buttestsusingtherealowneroftheprocess.

Returnstrueifstatisaregularfile(notadevicefile,pipe,socket,etc.).

File.stat("testfile").file?#=>true

Identifiesthetypeofstat.Thereturnstringisoneof:“file'',“directory'',“characterSpecial'',“blockSpecial'',“fifo'',“link'',“socket'',or“unknown''.

File.stat("/dev/tty").ftype#=>"characterSpecial"

Returnsthenumericgroupidoftheownerofstat.

File.stat("testfile").gid#=>500

Returnstrueiftheeffectivegroupidoftheprocessisthesameasthegroupidofstat.OnWindowsNT,

executable_real?→trueorfalse

file?→trueorfalse

ftype→string

gid→fixnum

grpowned?→trueorfalse

Page 272: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

returnsfalse.

File.stat("testfile").grpowned?#=>true

File.stat("/etc/passwd").grpowned?#=>false

Returnstheinodenumberforstat.

File.stat("testfile").ino#=>1083669

Produceanicelyformatteddescriptionofstat.

File.stat("/etc/passwd").inspect

#=>"#<File::Statdev=0xe000005,ino=1078078,mode=0100644,

#nlink=1,uid=0,gid=0,rdev=0x0,size=1374,blksize=4096,

#blocks=8,atime=WedDec1010:16:12CST2003,

#mtime=FriSep1215:41:41CDT2003,

#ctime=MonOct2711:20:27CST2003,

#birthtime=MonAug0408:13:49CDT2003>"

Returnsanintegerrepresentingthepermissionbitsofstat.Themeaningofthebitsisplatformdependent;onUnixsystems,seestat(2).

File.chmod(0644,"testfile")#=>1

s=File.stat("testfile")

sprintf("%o",s.mode)#=>"100644"

Returnsthemodificationtimeofstat.

File.stat("testfile").mtime#=>WedApr0908:53:14CDT2003

ino→fixnum

inspect→string

mode→fixnum

mtime→aTime

Page 273: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthenumberofhardlinkstostat.

File.stat("testfile").nlink#=>1

File.link("testfile","testfile.bak")#=>0

File.stat("testfile").nlink#=>2

Returnstrueiftheeffectiveuseridoftheprocessisthesameastheownerofstat.

File.stat("testfile").owned?#=>true

File.stat("/etc/passwd").owned?#=>false

Returnstrueiftheoperatingsystemsupportspipesandstatisapipe;falseotherwise.

Returnsanintegerrepresentingthedevicetypeonwhichstatresides.Returnsniliftheoperatingsystemdoesn'tsupportthisfeature.

File.stat("/dev/fd1").rdev#=>513

File.stat("/dev/tty").rdev#=>1280

ReturnsthemajorpartofFile_Stat#rdevornil.

File.stat("/dev/fd1").rdev_major#=>2

File.stat("/dev/tty").rdev_major#=>5

nlink→fixnum

owned?→trueorfalse

pipe?→trueorfalse

rdev→fixnumornil

rdev_major→fixnum

rdev_minor→fixnum

Page 274: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstheminorpartofFile_Stat#rdevornil.

File.stat("/dev/fd1").rdev_minor#=>1

File.stat("/dev/tty").rdev_minor#=>0

Returnstrueifstatisreadablebytheeffectiveuseridofthisprocess.

File.stat("testfile").readable?#=>true

Returnstrueifstatisreadablebytherealuseridofthisprocess.

File.stat("testfile").readable_real?#=>true

Returnstrueifstathastheset-group-idpermissionbitset,falseifitdoesn'toriftheoperatingsystemdoesn'tsupportthisfeature.

File.stat("/usr/sbin/lpc").setgid?#=>true

Returnstrueifstathastheset-user-idpermissionbitset,falseifitdoesn'toriftheoperatingsystemdoesn'tsupportthisfeature.

File.stat("/bin/su").setuid?#=>true

Returnsthesizeofstatinbytes.

readable?→trueorfalse

readable_real?→trueorfalse

setgid?→trueorfalse

setuid?→trueorfalse

size→fixnum

Page 275: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

File.stat("testfile").size#=>66

Returnsthesizeofstatinbytes.

File.stat("testfile").size#=>66

Returnstrueifstatisasocket,falseifitisn'toriftheoperatingsystemdoesn'tsupportthisfeature.

File.stat("testfile").socket?#=>false

Returnstrueifstathasitsstickybitset,falseifitdoesn'toriftheoperatingsystemdoesn'tsupportthisfeature.

File.stat("testfile").sticky?#=>false

Returnstrueifstatisasymboliclink,falseifitisn'toriftheoperatingsystemdoesn'tsupportthisfeature.AsFile::statautomaticallyfollowssymboliclinks,symlink?willalwaysbefalseforanobjectreturnedbyFile::stat.

File.symlink("testfile","alink")#=>0

File.stat("alink").symlink?#=>false

File.lstat("alink").symlink?#=>true

size→integer

socket?→trueorfalse

sticky?→trueorfalse

symlink?→trueorfalse

uid→fixnum

Page 276: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthenumericuseridoftheownerofstat.

File.stat("testfile").uid#=>501

Ifstatisreadablebyothers,returnsanintegerrepresentingthefilepermissionbitsofstat.Returnsnilotherwise.Themeaningofthebitsisplatformdependent;onUnixsystems,seestat(2).

m=File.stat("/etc/passwd").world_readable?#=>420

sprintf("%o",m)#=>"644"

Ifstatiswritablebyothers,returnsanintegerrepresentingthefilepermissionbitsofstat.Returnsnilotherwise.Themeaningofthebitsisplatformdependent;onUnixsystems,seestat(2).

m=File.stat("/tmp").world_writable?#=>511

sprintf("%o",m)#=>"777"

Returnstrueifstatiswritablebytheeffectiveuseridofthisprocess.

File.stat("testfile").writable?#=>true

Returnstrueifstatiswritablebytherealuseridofthisprocess.

File.stat("testfile").writable_real?#=>true

world_readable?→fixnumornil

world_writable?→fixnumornil

writable?→trueorfalse

writable_real?→trueorfalse

Page 277: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifstatisazero-lengthfile;falseotherwise.

File.stat("testfile").zero?#=>false

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

zero?→trueorfalse

Page 278: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleFileTestFileTestimplementsfiletestoperationssimilartothoseusedinFile::Stat.Itexistsasastandalonemodule,anditsmethodsarealsoinsinuatedintotheFileclass.(Notethatthisisnotdonebyinclusion:theinterpretercheats).

InFilesfile.c

PublicInstanceMethods

Returnstrueifthenamedfileisablockdevice.

file_namecanbeanIOobject.

Returnstrueifthenamedfileisacharacterdevice.

file_namecanbeanIOobject.

Returnstrueifthenamedfileisadirectory,orasymlinkthatpointsatadirectory,andfalseotherwise.

file_namecanbeanIOobject.

blockdev?(file_name)→trueorfalse

chardev?(file_name)→trueorfalse

directory?(file_name)→trueorfalse

Page 279: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

File.directory?(".")

Returnstrueifthenamedfileisexecutablebytheeffectiveuseridofthisprocess.

Returnstrueifthenamedfileisexecutablebytherealuseridofthisprocess.

Returntrueifthenamedfileexists.

file_namecanbeanIOobject.

“fileexists”meansthatstat()orfstat()systemcallissuccessful.

Deprecatedmethod.Don'tuse.

Returnstrueifthenamedfileexistsandisaregularfile.

filecanbeanIOobject.

Ifthefileargumentisasymboliclink,itwillresolvethesymboliclinkandusethefilereferencedbythelink.

Returnstrueifthenamedfileexistsandtheeffective

executable?(file_name)→trueorfalse

executable_real?(file_name)→trueorfalse

exist?(file_name)→trueorfalse

exists?(file_name)→trueorfalse

file?(file)→trueorfalse

grpowned?(file_name)→trueorfalse

Page 280: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

groupidofthecallingprocessistheownerofthefile.ReturnsfalseonWindows.

file_namecanbeanIOobject.

Returnstrueifthenamedfilesareidentical.

file_1andfile_2canbeanIOobject.

open("a","w"){}

pFile.identical?("a","a")#=>true

pFile.identical?("a","./a")#=>true

File.link("a","b")

pFile.identical?("a","b")#=>true

File.symlink("a","c")

pFile.identical?("a","c")#=>true

open("d","w"){}

pFile.identical?("a","d")#=>false

Returnstrueifthenamedfileexistsandtheeffectiveusedidofthecallingprocessistheownerofthefile.

file_namecanbeanIOobject.

Returnstrueifthenamedfileisapipe.

file_namecanbeanIOobject.

Returnstrueifthenamedfileisreadablebytheeffectiveuseridofthisprocess.

identical?(file_1,file_2)→trueorfalse

owned?(file_name)→trueorfalse

pipe?(file_name)→trueorfalse

readable?(file_name)→trueorfalse

readable_real?(file_name)→trueorfalse

Page 281: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthenamedfileisreadablebytherealuseridofthisprocess.

Returnstrueifthenamedfilehasthesetgidbitset.

Returnstrueifthenamedfilehasthesetuidbitset.

Returnsthesizeoffile_name.

file_namecanbeanIOobject.

Returnsniliffile_namedoesn'texistorhaszerosize,thesizeofthefileotherwise.

file_namecanbeanIOobject.

Returnstrueifthenamedfileisasocket.

file_namecanbeanIOobject.

Returnstrueifthenamedfilehasthestickybitset.

Returnstrueifthenamedfileisasymboliclink.

setgid?(file_name)→trueorfalse

setuid?(file_name)→trueorfalse

size(file_name)→integer

size?(file_name)→Integerornil

socket?(file_name)→trueorfalse

sticky?(file_name)→trueorfalse

symlink?(file_name)→trueorfalse

Page 282: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Iffile_nameisreadablebyothers,returnsanintegerrepresentingthefilepermissionbitsoffile_name.Returnsnilotherwise.Themeaningofthebitsisplatformdependent;onUnixsystems,seestat(2).

file_namecanbeanIOobject.

File.world_readable?("/etc/passwd")#=>420

m=File.world_readable?("/etc/passwd")

sprintf("%o",m)#=>"644"

Iffile_nameiswritablebyothers,returnsanintegerrepresentingthefilepermissionbitsoffile_name.Returnsnilotherwise.Themeaningofthebitsisplatformdependent;onUnixsystems,seestat(2).

file_namecanbeanIOobject.

File.world_writable?("/tmp")#=>511

m=File.world_writable?("/tmp")

sprintf("%o",m)#=>"777"

Returnstrueifthenamedfileiswritablebytheeffectiveuseridofthisprocess.

Returnstrueifthenamedfileiswritablebytherealuseridofthisprocess.

world_readable?(file_name)→fixnumornil

world_writable?(file_name)→fixnumornil

writable?(file_name)→trueorfalse

writable_real?(file_name)→trueorfalse

zero?(file_name)→trueorfalse

Page 283: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthenamedfileexistsandhasazerosize.

file_namecanbeanIOobject.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 284: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classFixnumHoldsIntegervaluesthatcanberepresentedinanativemachineword(minus1bit).IfanyoperationonaFixnumexceedsthisrange,thevalueisautomaticallyconvertedtoaBignum.

Fixnumobjectshaveimmediatevalue.Thismeansthatwhentheyareassignedorpassedasparameters,theactualobjectispassed,ratherthanareferencetothatobject.

AssignmentdoesnotaliasFixnumobjects.ThereiseffectivelyonlyoneFixnumobjectinstanceforanygivenintegervalue,so,forexample,youcannotaddasingletonmethodtoaFixnum.AnyattempttoaddasingletonmethodtoaFixnumobjectwillraiseaTypeError.

InFilesnumeric.c

ParentInteger

PublicInstanceMethods

Page 285: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsfixmoduloother.

SeeNumeric#divmodformoreinformation.

BitwiseAND.

Performsmultiplication:theclassoftheresultingobjectdependsontheclassofnumericandonthemagnitudeoftheresult.ItmayreturnaBignum.

Raisesfixtothepowerofnumeric,whichmaybenegativeorfractional.

2**3#=>8

2**-1#=>(1/2)

2**0.5#=>1.4142135623731

Performsaddition:theclassoftheresultingobjectdependsontheclassofnumericandonthemagnitudeoftheresult.ItmayreturnaBignum.

Performssubtraction:theclassoftheresultingobjectdependsontheclassofnumericandonthemagnitudeoftheresult.ItmayreturnaBignum.

fix%other→realmodulo(other)→real

fix&integer→integer_result

fix*numeric→numeric_result

fix**numeric→numeric_result

fix+numeric→numeric_result

fix-numeric→numeric_result

Page 286: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Negatesfix,whichmayreturnaBignum.

Performsdivision:theclassoftheresultingobjectdependsontheclassofnumericandonthemagnitudeoftheresult.ItmayreturnaBignum.

Returnstrueifthevalueoffixislessthanthatofreal.

Shiftsfixleftcountpositions,orrightifcountisnegative.

Returnstrueifthevalueoffixislessthanorequaltothatofreal.

Comparison—Returns-1,0,+1ornildependingonwhetherfixislessthan,equalto,orgreaterthannumeric.

ThisisthebasisforthetestsintheComparablemodule.

nilisreturnedifthetwovaluesareincomparable.

-fix→integer

fix/numeric→numeric_result

fix<real→trueorfalse

fix<<count→integer

fix<=real→trueorfalse

fix<=>numeric→-1,0,+1ornil

fix==other→trueorfalse

Page 287: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returntrueiffixequalsothernumerically.

1==2#=>false

1==1.0#=>true

Returntrueiffixequalsothernumerically.

1==2#=>false

1==1.0#=>true

Returnstrueifthevalueoffixisgreaterthanthatofreal.

Returnstrueifthevalueoffixisgreaterthanorequaltothatofreal.

Shiftsfixrightcountpositions,orleftifcountisnegative.

BitReference—Returnsthe+n+thbitinthebinaryrepresentationoffix,wherefix[0]istheleastsignificantbit.

Forexample:

a=0b11001100101010

30.downto(0)do|n|printa[n]end

#=>0000000000000000011001100101010

fix==other→trueorfalse

fix>real→trueorfalse

fix>=real→trueorfalse

fix>>count→integer

fix[n]→0,1

Page 288: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

BitwiseEXCLUSIVEOR.

Returnstheabsolutevalueoffix.

-12345.abs#=>12345

12345.abs#=>12345

Returnsthenumberofbitsofthevalueofint.

“thenumberofbits”meansthatthebitpositionofthehighestbitwhichisdifferenttothesignbit.(Thebitpositionofthebit2**nisn+1.)Ifthereisnosuchbit(zeroorminusone),zeroisreturned.

I.e.Thismethodreturnsceil(log2(int<0?-int:int+1)).

(-2**12-1).bit_length#=>13

(-2**12).bit_length#=>12

(-2**12+1).bit_length#=>12

-0x101.bit_length#=>9

-0x100.bit_length#=>8

-0xff.bit_length#=>8

-2.bit_length#=>1

-1.bit_length#=>0

0.bit_length#=>0

1.bit_length#=>1

0xff.bit_length#=>8

0x100.bit_length#=>9

(2**12-1).bit_length#=>12

(2**12).bit_length#=>13

(2**12+1).bit_length#=>13

ThismethodcanbeusedtodetectoverflowinArray#packasfollows.

fix^integer→integer_result

abs→integermagnitude→integer

bit_length→integer

Page 289: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ifn.bit_length<32

[n].pack("l")#nooverflow

else

raise"overflow"

end

Performsintegerdivision:returnsintegerresultofdividingfixbynumeric.

SeeNumeric#divmod.

Returnstrueiffixisanevennumber.

Returnsthefloatingpointresultofdividingfixbynumeric.

654321.fdiv(13731)#=>47.6528293642124

654321.fdiv(13731.24)#=>47.6519964693647

Aliasfor:to_s

Returnstheabsolutevalueoffix.

-12345.abs#=>12345

12345.abs#=>12345

div(numeric)→integer

divmod(numeric)→array

even?→trueorfalse

fdiv(numeric)→float

inspect(p1=v1)

abs→integermagnitude→integer

Page 290: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsfixmoduloother.

SeeNumeric#divmodformoreinformation.

Returnstrueiffixisanoddnumber.

Returnsthenumberofbytesinthemachinerepresentationoffix.

1.size#=>4

-1.size#=>4

2147483647.size#=>4

ReturnstheIntegerequaltoint+1.

1.next#=>2

(-1).next#=>0

ConvertsfixtoaFloat.

Returnsastringcontainingtherepresentationoffixradixbase(between2and36).

12345.to_s#=>"12345"

fix%other→realmodulo(other)→real

odd?→trueorfalse

size→fixnum

next→integersucc→integer

to_f→float

to_s(base=10)→string

Page 291: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

12345.to_s(2)#=>"11000000111001"

12345.to_s(8)#=>"30071"

12345.to_s(10)#=>"12345"

12345.to_s(16)#=>"3039"

12345.to_s(36)#=>"9ix"

Alsoaliasedas:inspect

Returnstrueiffixiszero.

BitwiseOR.

One'scomplement:returnsanumberwhereeachbitisflipped.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

zero?→trueorfalse

fix|integer→integer_result

~fix→integer

Page 292: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classFloatFloatobjectsrepresentinexactrealnumbersusingthenativearchitecture'sdouble-precisionfloatingpointrepresentation.

Floatingpointhasadifferentarithmeticandisaninexactnumber.Soyoushouldknowitsesotericsystem.seefollowing:

docs.sun.com/source/806-3568/ncg_goldberg.htmlwiki.github.com/rdp/ruby_tutorials_core/ruby-talk-faq#wiki-floats_impreciseen.wikipedia.org/wiki/Floating_point#Accuracy_problems

InFilescomplex.cnumeric.crational.c

ParentNumeric

Constants

DIG

Page 293: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Theminimumnumberofsignificantdecimaldigitsinadouble-precisionfloatingpoint.

Usuallydefaultsto15.

EPSILON

Thedifferencebetween1andthesmallestdouble-precisionfloatingpointnumbergreaterthan1.

Usuallydefaultsto2.2204460492503131e-16.

INFINITY

Anexpressionrepresentingpositiveinfinity.

MANT_DIG

Thenumberofbasedigitsforthedoubledatatype.

Usuallydefaultsto53.

MAX

Thelargestpossibleintegerinadouble-precisionfloatingpointnumber.

Usuallydefaultsto1.7976931348623157e+308.

MAX_10_EXP

Thelargestpositiveexponentinadouble-precisionfloatingpointwhere10raisedtothispowerminus1.

Usuallydefaultsto308.

MAX_EXP

Thelargestpossibleexponentvalueinadouble-precisionfloatingpoint.

Page 294: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Usuallydefaultsto1024.

MIN

MIN.0.0.next_floatreturnsthesmallestpositivefloatingpointnumberincludingdenormalizednumbers.

MIN_10_EXP

Thesmallestnegativeexponentinadouble-precisionfloatingpointwhere10raisedtothispowerminus1.

Usuallydefaultsto-307.

MIN_EXP

Thesmallestposableexponentvalueinadouble-precisionfloatingpoint.

Usuallydefaultsto-1021.

NAN

Anexpressionrepresentingavaluewhichis“notanumber”.

RADIX

Thebaseofthefloatingpoint,ornumberofuniquedigitsusedtorepresentthenumber.

Usuallydefaultsto2onmostsystems,whichwouldrepresentabase-10decimal.

ROUNDS

Roundingtowardsnegativeinfinity

Page 295: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PublicInstanceMethods

Returnthemoduloafterdivisionoffloatbyother.

6543.21.modulo(137)#=>104.21

6543.21.modulo(137.24)#=>92.9299999999996

Returnsanewfloatwhichistheproductoffloatandother.

Raisesfloattothepowerofother.

2.0**3#=>8.0

Returnsanewfloatwhichisthesumoffloatandother.

Returnsanewfloatwhichisthedifferenceoffloatandother.

Returnsfloat,negated.

float%other→floatmodulo(other)→float

float*other→float

float**other→float

float+other→float

float-other→float

-float→float

float/other→float

Page 296: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanewfloatwhichistheresultofdividingfloatbyother.

Returnstrueiffloatislessthanreal.

TheresultofNaN<NaNisundefined,sotheimplementation-dependentvalueisreturned.

Returnstrueiffloatislessthanorequaltoreal.

TheresultofNaN<=NaNisundefined,sotheimplementation-dependentvalueisreturned.

Returns-1,0,+1ornildependingonwhetherfloatislessthan,equalto,orgreaterthanreal.ThisisthebasisforthetestsinComparable.

TheresultofNaN<=>NaNisundefined,sotheimplementation-dependentvalueisreturned.

nilisreturnedifthetwovaluesareincomparable.

Returnstrueonlyifobjhasthesamevalueasfloat.Contrastthiswith#eql?,whichrequiresobjtobeaFloat.

TheresultofNaN==NaNisundefined,sotheimplementation-dependentvalueisreturned.

1.0==1#=>true

float<real→trueorfalse

float<=real→trueorfalse

float<=>real→-1,0,+1ornil

float==obj→trueorfalse

Page 297: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueonlyifobjhasthesamevalueasfloat.Contrastthiswith#eql?,whichrequiresobjtobeaFloat.

TheresultofNaN==NaNisundefined,sotheimplementation-dependentvalueisreturned.

1.0==1#=>true

Returnstrueiffloatisgreaterthanreal.

TheresultofNaN>NaNisundefined,sotheimplementation-dependentvalueisreturned.

Returnstrueiffloatisgreaterthanorequaltoreal.

TheresultofNaN>=NaNisundefined,sotheimplementation-dependentvalueisreturned.

Returnstheabsolutevalueoffloat.

(-34.56).abs#=>34.56

-34.56.abs#=>34.56

Returns0ifthevalueispositive,piotherwise.

float==obj→trueorfalse

float>real→trueorfalse

float>=real→trueorfalse

abs→floatmagnitude→float

arg→0orfloatangle→0orfloatphase→0orfloat

Page 298: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returns0ifthevalueispositive,piotherwise.

ReturnsthesmallestIntegergreaterthanorequaltofloat.

1.2.ceil#=>2

2.0.ceil#=>2

(-1.2).ceil#=>-1

(-2.0).ceil#=>-2

ReturnsanarraywithbothanumericandafloatrepresentedasFloatobjects.

ThisisachievedbyconvertinganumerictoaFloat.

1.2.coerce(3)#=>[3.0,1.2]

2.5.coerce(1.1)#=>[1.1,2.5]

Returnsthedenominator(alwayspositive).Theresultismachinedependent.

Seenumerator.

SeeNumeric#divmod.

42.0.divmod6#=>[7,0.0]

42.0.divmod5#=>[8,2.0]

arg→0orfloatangle→0orfloatphase→0orfloat

ceil→integer

coerce(numeric)→array

denominator→integer

divmod(numeric)→array

Page 299: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstrueonlyifobjisaFloatwiththesamevalueasfloat.ContrastthiswithFloat#==,whichperformstypeconversions.

TheresultofNaN.eql?(NaN)isundefined,sotheimplementation-dependentvalueisreturned.

1.0.eql?(1)#=>false

Returnsfloat/numeric,sameasFloat#/.

ReturnstrueiffloatisavalidIEEEfloatingpointnumber(itisnotinfinite,and#nan?isfalse).

Returnsthelargestintegerlessthanorequaltofloat.

1.2.floor#=>1

2.0.floor#=>2

(-1.2).floor#=>-2

(-2.0).floor#=>-2

Returnsahashcodeforthisfloat.

SeealsoObject#hash.

eql?(obj)→trueorfalse

fdiv(numeric)→floatquo(numeric)→float

finite?→trueorfalse

floor→integer

hash→integer

infinite?→nil,-1,+1

Page 300: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnvaluescorrespondingtothevalueoffloat:finite

nil

-Infinity

-1

+Infinity1

Forexample:

(0.0).infinite?#=>nil

(-1.0/0.0).infinite?#=>-1

(+1.0/0.0).infinite?#=>1

Aliasfor:to_s

Returnstheabsolutevalueoffloat.

(-34.56).abs#=>34.56

-34.56.abs#=>34.56

Returnthemoduloafterdivisionoffloatbyother.

6543.21.modulo(137)#=>104.21

6543.21.modulo(137.24)#=>92.9299999999996

ReturnstrueiffloatisaninvalidIEEEfloatingpoint

inspect()

abs→floatmagnitude→float

float%other→floatmodulo(other)→float

nan?→trueorfalse

Page 301: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

number.

a=-1.0#=>-1.0

a.nan?#=>false

a=0.0/0.0#=>NaN

a.nan?#=>true

Returnsthenextrepresentablefloating-pointnumber.

Float::MAX.next_floatandFloat::INFINITY.next_floatisFloat::INFINITY.

Float::NAN.next_floatisFloat::NAN.

Forexample:

p0.01.next_float#=>0.010000000000000002

p1.0.next_float#=>1.0000000000000002

p100.0.next_float#=>100.00000000000001

p0.01.next_float-0.01#=>1.734723475976807e-18

p1.0.next_float-1.0#=>2.220446049250313e-16

p100.0.next_float-100.0#=>1.4210854715202004e-14

f=0.01;20.times{printf"%-20a%s\n",f,f.to_s;f

#=>0x1.47ae147ae147bp-70.01

#0x1.47ae147ae147cp-70.010000000000000002

#0x1.47ae147ae147dp-70.010000000000000004

#0x1.47ae147ae147ep-70.010000000000000005

#0x1.47ae147ae147fp-70.010000000000000007

#0x1.47ae147ae148p-70.010000000000000009

#0x1.47ae147ae1481p-70.01000000000000001

#0x1.47ae147ae1482p-70.010000000000000012

#0x1.47ae147ae1483p-70.010000000000000014

#0x1.47ae147ae1484p-70.010000000000000016

#0x1.47ae147ae1485p-70.010000000000000018

#0x1.47ae147ae1486p-70.01000000000000002

#0x1.47ae147ae1487p-70.010000000000000021

#0x1.47ae147ae1488p-70.010000000000000023

#0x1.47ae147ae1489p-70.010000000000000024

#0x1.47ae147ae148ap-70.010000000000000026

#0x1.47ae147ae148bp-70.010000000000000028

#0x1.47ae147ae148cp-70.01000000000000003

#0x1.47ae147ae148dp-70.010000000000000031

next_float→float

Page 302: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#0x1.47ae147ae148ep-70.010000000000000033

f=0.0

100.times{f+=0.1}

pf#=>9.99999999999998#shouldbe10.0intheidealworld.

p10-f#=>1.9539925233402755e-14#thefloating-pointerror.

p(10.0.next_float-10)#=>1.7763568394002505e-15#1ulp(unitsinthelastplace).

p((10-f)/(10.0.next_float-10))#=>11.0#theerroris11ulp.

p((10-f)/(10*Float::EPSILON))#=>8.8#approximationoftheabove.

p"%a"%f#=>"0x1.3fffffffffff5p+3"#thelasthexdigitis5.16-5=11ulp.

Returnsthenumerator.Theresultismachinedependent.

n=0.3.numerator#=>5404319552844595

d=0.3.denominator#=>18014398509481984

n.fdiv(d)#=>0.3

Returns0ifthevalueispositive,piotherwise.

Returnsthepreviousrepresentablefloatint-pointnumber.

(-Float::MAX).#prev_floatand(-Float::INFINITY).#prev_floatis-Float::INFINITY.

Float::NAN.prev_floatisFloat::NAN.

Forexample:

p0.01.prev_float#=>0.009999999999999998

p1.0.prev_float#=>0.9999999999999999

p100.0.prev_float#=>99.99999999999999

numerator→integer

arg→0orfloatangle→0orfloatphase→0orfloat

prev_float→float

Page 303: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

p0.01-0.01.prev_float#=>1.734723475976807e-18

p1.0-1.0.prev_float#=>1.1102230246251565e-16

p100.0-100.0.prev_float#=>1.4210854715202004e-14

f=0.01;20.times{printf"%-20a%s\n",f,f.to_s;f

#=>0x1.47ae147ae147bp-70.01

#0x1.47ae147ae147ap-70.009999999999999998

#0x1.47ae147ae1479p-70.009999999999999997

#0x1.47ae147ae1478p-70.009999999999999995

#0x1.47ae147ae1477p-70.009999999999999993

#0x1.47ae147ae1476p-70.009999999999999992

#0x1.47ae147ae1475p-70.00999999999999999

#0x1.47ae147ae1474p-70.009999999999999988

#0x1.47ae147ae1473p-70.009999999999999986

#0x1.47ae147ae1472p-70.009999999999999985

#0x1.47ae147ae1471p-70.009999999999999983

#0x1.47ae147ae147p-70.009999999999999981

#0x1.47ae147ae146fp-70.00999999999999998

#0x1.47ae147ae146ep-70.009999999999999978

#0x1.47ae147ae146dp-70.009999999999999976

#0x1.47ae147ae146cp-70.009999999999999974

#0x1.47ae147ae146bp-70.009999999999999972

#0x1.47ae147ae146ap-70.00999999999999997

#0x1.47ae147ae1469p-70.009999999999999969

#0x1.47ae147ae1468p-70.009999999999999967

Returnsfloat/numeric,sameasFloat#/.

Returnsasimplerapproximationofthevalue(flt-|eps|<=result<=flt+|eps|).iftheoptionalepsisnotgiven,itwillbechosenautomatically.

0.3.rationalize#=>(3/10)

1.333.rationalize#=>(1333/1000)

1.333.rationalize(0.01)#=>(4/3)

Seeto_r.

fdiv(numeric)→floatquo(numeric)→float

rationalize([eps])→rational

Page 304: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Roundsfloattoagivenprecisionindecimaldigits(default0digits).

Precisionmaybenegative.Returnsafloatingpointnumberwhenndigitsismorethanzero.

1.4.round#=>1

1.5.round#=>2

1.6.round#=>2

(-1.5).round#=>-2

1.234567.round(2)#=>1.23

1.234567.round(3)#=>1.235

1.234567.round(4)#=>1.2346

1.234567.round(5)#=>1.23457

34567.89.round(-5)#=>0

34567.89.round(-4)#=>30000

34567.89.round(-3)#=>35000

34567.89.round(-2)#=>34600

34567.89.round(-1)#=>34570

34567.89.round(0)#=>34568

34567.89.round(1)#=>34567.9

34567.89.round(2)#=>34567.89

34567.89.round(3)#=>34567.89

Sincefloatisalreadyafloat,returnsself.

ReturnsthefloattruncatedtoanInteger.

Synonymsareto_i,to_int,andtruncate.

round([ndigits])→integerorfloat

to_f→self

to_i→integerto_int→integertruncate→integer

Page 305: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsthefloattruncatedtoanInteger.

Synonymsareto_i,to_int,andtruncate.

Returnsthevalueasarational.

NOTE:0.3.to_risn'tthesameas'0.3'.to_r.Thelatterisequivalentto'3/10'.#to_r,buttheformerisn'tso.

2.0.to_r#=>(2/1)

2.5.to_r#=>(5/2)

-0.75.to_r#=>(-3/4)

0.0.to_r#=>(0/1)

Seerationalize.

Returnsastringcontainingarepresentationofself.Aswellasafixedorexponentialformofthefloat,thecallmayreturnNaN,Infinity,and-Infinity.

Alsoaliasedas:inspect

ReturnsthefloattruncatedtoanInteger.

Synonymsareto_i,to_int,andtruncate.

to_i→integerto_int→integertruncate→integer

to_r→rational

to_s→string

to_i→integerto_int→integertruncate→integer

zero?→trueorfalse

Page 306: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueiffloatis0.0.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 307: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classFloatDomainErrorRaisedwhenattemptingtoconvertspecialfloatvalues(inparticularinfiniteorNaN)tonumericalclasseswhichdon'tsupportthem.

Float::INFINITY.to_r

#=>FloatDomainError:Infinity

InFilesnumeric.c

ParentRangeError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 308: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleGCTheGCmoduleprovidesaninterfacetoRuby'smarkandsweepgarbagecollectionmechanism.

SomeoftheunderlyingmethodsarealsoavailableviatheObjectSpacemodule.

YoumayobtaininformationabouttheoperationoftheGCthroughGC::Profiler.

InFilesgc.c

Constants

INTERNAL_CONSTANTS

OPTS

PublicClassMethods

ThenumberoftimesGCoccurred.

ItreturnsthenumberoftimesGCoccurredsincetheprocessstarted.

count→Integer

Page 309: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Disablesgarbagecollection,returningtrueifgarbagecollectionwasalreadydisabled.

GC.disable#=>false

GC.disable#=>true

Enablesgarbagecollection,returningtrueifgarbagecollectionwaspreviouslydisabled.

GC.disable#=>false

GC.enable#=>true

GC.enable#=>false

Returnsinformationaboutthemostrecentgarbagecollection.

Returnsthesizeofmemoryallocatedbymalloc().

OnlyavailableifrubywasbuiltwithCALC_EXACT_MALLOC_SIZE.

Returnsthenumberofmalloc()allocations.

OnlyavailableifrubywasbuiltwithCALC_EXACT_MALLOC_SIZE.

disable→trueorfalse

enable→trueorfalse

latest_gc_info->{:gc_by→:newobj}latest_gc_info(hash)→hashlatest_gc_info(:major_by)→:malloc

malloc_allocated_size→Integer

malloc_allocations→Integer

Page 310: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Initiatesgarbagecollection,unlessmanuallydisabled.

Thismethodisdefinedwithkeywordargumentsthatdefaulttotrue:

defGC.start(full_mark:true,immediate_sweep:true);

Usefull_mark:falsetoperformaminorGC.Useimmediate_sweep:falsetodefersweeping(uselazysweep).

Note:Thesekeywordargumentsareimplementationandversiondependent.Theyarenotguaranteedtobefuture-compatible,andmaybeignorediftheunderlyingimplementationdoesnotsupportthem.

ReturnsaHashcontaininginformationabouttheGC.

ThehashincludesinformationaboutinternalstatisticsaboutGCsuchas:

{

:count=>0,

:heap_allocated_pages=>24,

:heap_sorted_length=>24,

:heap_allocatable_pages=>0,

:heap_available_slots=>9783,

:heap_live_slots=>7713,

start→nilgarbage_collect→nilstart(full_mark:true,immediate_sweep:true)→nilgarbage_collect(full_mark:true,immediate_sweep:true)→nil

stat→Hashstat(hash)→hashstat(:key)→Numeric

Page 311: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

:heap_free_slots=>2070,

:heap_final_slots=>0,

:heap_marked_slots=>0,

:heap_swept_slots=>0,

:heap_eden_pages=>24,

:heap_tomb_pages=>0,

:total_allocated_pages=>24,

:total_freed_pages=>0,

:total_allocated_objects=>7796,

:total_freed_objects=>83,

:malloc_increase_bytes=>2389312,

:malloc_increase_bytes_limit=>16777216,

:minor_gc_count=>0,

:major_gc_count=>0,

:remembered_wb_unprotected_objects=>0,

:remembered_wb_unprotected_objects_limit=>0,

:old_objects=>0,

:old_objects_limit=>0,

:oldmalloc_increase_bytes=>2389760,

:oldmalloc_increase_bytes_limit=>16777216

}

Thecontentsofthehashareimplementationspecificandmaybechangedinthefuture.

ThismethodisonlyexpectedtoworkonCRuby.

ReturnscurrentstatusofGCstressmode.

UpdatestheGCstressmode.

Whenstressmodeisenabled,theGCisinvokedateveryGCopportunity:allmemoryandobjectallocations.

Enablingstressmodewilldegradeperformance,itisonlyfordebugging.

flagcanbetrue,false,orafixnumbit-ORedfollowingflags.

stress→fixnum,trueorfalse

stress=flag→flag

Page 312: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

0x01::nomajorGC

0x02::noimmediatesweep

0x04::fullmarkaftermalloc/calloc/realloc

Verifyinternalconsistency.

Thismethodisimplementationspecific.NowthismethodchecksgenerationalconsistencyifRGenGCissupported.

PublicInstanceMethods

Initiatesgarbagecollection,unlessmanuallydisabled.

Thismethodisdefinedwithkeywordargumentsthatdefaulttotrue:

defGC.start(full_mark:true,immediate_sweep:true);

Usefull_mark:falsetoperformaminorGC.Useimmediate_sweep:falsetodefersweeping(uselazysweep).

Note:Thesekeywordargumentsareimplementationandversiondependent.Theyarenotguaranteedtobefuture-compatible,andmaybeignorediftheunderlyingimplementationdoesnotsupportthem.

verify_internal_consistency→nil

start→nilgarbage_collect→nilstart(full_mark:true,immediate_sweep:true)→nilgarbage_collect(full_mark:true,immediate_sweep:true)→nil

Page 313: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 314: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleGC::ProfilerTheGCprofilerprovidesaccesstoinformationonGCrunsincludingtime,lengthandobjectspacesize.

Example:

GC::Profiler.enable

require'rdoc/rdoc'

GC::Profiler.report

GC::Profiler.disable

SeealsoGC.count,GC.malloc_allocated_sizeandGC.malloc_allocations

InFilesgc.c

PublicClassMethods

ClearstheGCprofilerdata.

StopstheGCprofiler.

GC::Profiler.clear→nil

GC::Profiler.disable→nil

Page 315: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

StartstheGCprofiler.

ThecurrentstatusofGCprofilemode.

ReturnsanArrayofindividualrawprofiledataHashesorderedfromearliesttolatestby:GC_INVOKE_TIME.

Forexample:

[

{

:GC_TIME=>1.3000000000000858e-05,

:GC_INVOKE_TIME=>0.010634999999999999,

:HEAP_USE_SIZE=>289640,

:HEAP_TOTAL_SIZE=>588960,

:HEAP_TOTAL_OBJECTS=>14724,

:GC_IS_MARKED=>false

},

#...

]

Thekeysmean::GC_TIME

TimeelapsedinsecondsforthisGCrun

:GC_INVOKE_TIME

TimeelapsedinsecondsfromstartuptowhentheGCwasinvoked

:HEAP_USE_SIZE

Totalbytesofheapused

:HEAP_TOTAL_SIZE

Totalsizeofheapinbytes

GC::Profiler.enable→nil

GC::Profiler.enabled?→trueorfalse

GC::Profiler.raw_data→[Hash,...]

Page 316: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

:HEAP_TOTAL_OBJECTS

Totalnumberofobjects

:GC_IS_MARKED

ReturnstrueiftheGCisinmarkphase

IfrubywasbuiltwithGC_PROFILE_MORE_DETAIL,youwillalsohaveaccesstothefollowinghashkeys::GC_MARK_TIME

:GC_SWEEP_TIME

:ALLOCATE_INCREASE

:ALLOCATE_LIMIT

:HEAP_USE_PAGES

:HEAP_LIVE_OBJECTS

:HEAP_FREE_OBJECTS

:HAVE_FINALIZE

Writesthe::resultto$stdoutorthegivenIOobject.

Returnsaprofiledatareportsuchas:

GC1invokes.

IndexInvokeTime(sec)UseSize(byte)TotalSize(byte)TotalObjectGCtime(ms)

10.012159240212940106470.00000000000001530000

Thetotaltimeusedforgarbagecollectioninseconds

GeneratedbyRDoc3.12.2.

GC::Profiler.reportGC::Profiler.report(io)

GC::Profiler.result→String

GC::Profiler.total_time→float

Page 317: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedwiththeDarkfishRdocGenerator3.

Page 318: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classHashAHashisadictionary-likecollectionofuniquekeysandtheirvalues.Alsocalledassociativearrays,theyaresimilartoArrays,butwhereanArrayusesintegersasitsindex,aHashallowsyoutouseanyobjecttype.

Hashesenumeratetheirvaluesintheorderthatthecorrespondingkeyswereinserted.

AHashcanbeeasilycreatedbyusingitsimplicitform:

grades={"JaneDoe"=>10,"JimDoe"=>6}

Hashesallowanalternatesyntaxformwhenyourkeysarealwayssymbols.Insteadof

options={:font_size=>10,:font_family=>"Arial"

Youcouldwriteitas:

options={font_size:10,font_family:"Arial"}

Eachnamedkeyisasymbolyoucanaccessinhash:

options[:font_size]#=>10

Page 319: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

AHashcanalsobecreatedthroughits::newmethod:

grades=Hash.new

grades["DorothyDoe"]=9

Hasheshaveadefaultvaluethatisreturnedwhenaccessingkeysthatdonotexistinthehash.Ifnodefaultissetnilisused.Youcansetthedefaultvaluebysendingitasanargumentto::new:

grades=Hash.new(0)

Orbyusingthedefault=method:

grades={"TimmyDoe"=>8}

grades.default=0

AccessingavalueinaHashrequiresusingitskey:

putsgrades["JaneDoe"]#=>0

CommonUses

Hashesareaneasywaytorepresentdatastructures,suchas

books={}

books[:matz]="TheRubyLanguage"

books[:black]="TheWell-GroundedRubyist"

Page 320: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Hashesarealsocommonlyusedasawaytohavenamedparametersinfunctions.Notethatnobracketsareusedbelow.Ifahashisthelastargumentonamethodcall,nobracesareneeded,thuscreatingareallycleaninterface:

Person.create(name:"JohnDoe",age:27)

defself.create(params)

@name=params[:name]

@age=params[:age]

end

HashKeys

Twoobjectsrefertothesamehashkeywhentheirhashvalueisidenticalandthetwoobjectsareeql?toeachother.

Auser-definedclassmaybeusedasahashkeyifthehashandeql?methodsareoverriddentoprovidemeaningfulbehavior.Bydefault,separateinstancesrefertoseparatehashkeys.

Atypicalimplementationofhashisbasedontheobject'sdatawhileeql?isusuallyaliasedtotheoverridden==method:

classBook

attr_reader:author,:title

definitialize(author,title)

@author=author

@title=title

Page 321: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

def==(other)

self.class===otherand

other.author==@authorand

other.title==@title

end

aliaseql?==

defhash

@author.hash^@title.hash#XOR

end

end

book1=Book.new'matz','RubyinaNutshell'

book2=Book.new'matz','RubyinaNutshell'

reviews={}

reviews[book1]='Greatreference!'

reviews[book2]='Niceandcompact!'

reviews.length#=>1

SeealsoObject#hashandObject#eql?

InFileshash.c

ParentObject

IncludedModules

Page 322: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Enumerable

PublicClassMethods

Createsanewhashpopulatedwiththegivenobjects.

Similartotheliteral{key=>value,...}.Inthefirstform,keysandvaluesoccurinpairs,sotheremustbeanevennumberofarguments.

Thesecondandthirdformtakeasingleargumentwhichiseitheranarrayofkey-valuepairsoranobjectconvertibletoahash.

Hash["a",100,"b",200]#=>{"a"=>100,"b"=>200}

Hash[[["a",100],["b",200]]]#=>{"a"=>100,"b"=>200}

Hash["a"=>100,"b"=>200]#=>{"a"=>100,"b"=>200}

Returnsanew,emptyhash.Ifthishashissubsequentlyaccessedbyakeythatdoesn'tcorrespondtoahashentry,thevaluereturneddependsonthestyleofnewusedtocreatethehash.Inthefirstform,theaccessreturnsnil.Ifobjisspecified,thissingleobjectwillbeusedforalldefaultvalues.Ifablockisspecified,itwillbecalledwiththehashobjectandthekey,andshouldreturnthedefaultvalue.Itistheblock'sresponsibilitytostorethevalueinthehashifrequired.

Hash[key,value,...]→new_hashHash[[[key,value],...]]→new_hashHash[object]→new_hash

new→new_hashnew(obj)→new_hashnew{|hash,key|block}→new_hash

Page 323: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

h=Hash.new("GoFish")

h["a"]=100

h["b"]=200

h["a"]#=>100

h["c"]#=>"GoFish"

#Thefollowingaltersthesingledefaultobject

h["c"].upcase!#=>"GOFISH"

h["d"]#=>"GOFISH"

h.keys#=>["a","b"]

#Whilethiscreatesanewdefaultobjecteachtime

h=Hash.new{|hash,key|hash[key]="GoFish:#{key}"

h["c"]#=>"GoFish:c"

h["c"].upcase!#=>"GOFISH:C"

h["d"]#=>"GoFish:d"

h.keys#=>["c","d"]

Trytoconvertobjintoahash,using#to_hashmethod.Returnsconvertedhashornilifobjcannotbeconvertedforanyreason.

Hash.try_convert({1=>2})#=>{1=>2}

Hash.try_convert("1=>2")#=>nil

PublicInstanceMethods

Equality—Twohashesareequaliftheyeachcontainthesamenumberofkeysandifeachkey-valuepairisequalto(accordingtoObject#==)thecorrespondingelementsintheotherhash.

h1={"a"=>1,"c"=>2}

h2={7=>35,"c"=>2,"a"=>1}

h3={"a"=>1,"c"=>2,7=>35}

h4={"a"=>1,"d"=>2,"f"=>35}

try_convert(obj)→hashornil

hsh==other_hash→trueorfalse

Page 324: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

h1==h2#=>false

h2==h3#=>true

h3==h4#=>false

ElementReference—Retrievesthevalueobjectcorrespondingtothekeyobject.Ifnotfound,returnsthedefaultvalue(seeHash::newfordetails).

h={"a"=>100,"b"=>200}

h["a"]#=>100

h["c"]#=>nil

hsh[key]→value

hsh[key]=value→valuestore(key,value)→value

Page 325: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Associatesthevaluegivenbyvaluewiththekeygivenbykey.

h={"a"=>100,"b"=>200}

h["a"]=9

h["c"]=4

h#=>{"a"=>9,"b"=>200,"c"=>4}

h.store("d",42)#=>42

h#=>{"a"=>9,"b"=>200,"c"=>4,"d"=>42}

keyshouldnothaveitsvaluechangedwhileitisinuseasakey(anunfrozenStringpassedasakeywillbeduplicatedandfrozen).

a="a"

b="b".freeze

h={a=>100,b=>200}

h.key(100).equal?a#=>false

h.key(200).equal?b#=>true

SeealsoEnumerable#any?

Searchesthroughthehashcomparingobjwiththekeyusing==.Returnsthekey-valuepair(twoelementsarray)ornilifnomatchisfound.SeeArray#assoc.

h={"colors"=>["red","blue","green"],

"letters"=>["a","b","c"]}

h.assoc("letters")#=>["letters",["a","b","c"]]

h.assoc("foo")#=>nil

ElementAssignment

any?[{|(key,value)|block}]→trueorfalse

assoc(obj)→an_arrayornil

Page 326: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Removesallkey-valuepairsfromhsh.

h={"a"=>100,"b"=>200}#=>{"a"=>100,"b"=>200}

h.clear#=>{}

Makeshshcompareitskeysbytheiridentity,i.e.itwillconsiderexactsameobjectsassamekeys.

h1={"a"=>100,"b"=>200,:c=>"c"}

h1["a"]#=>100

h1.compare_by_identity

h1.compare_by_identity?#=>true

h1["a".dup]#=>nil#differentobjects.

h1[:c]#=>"c"#samesymbolsareallsame.

Returnstrueifhshwillcompareitskeysbytheiridentity.AlsoseeHash#compare_by_identity.

Returnsthedefaultvalue,thevaluethatwouldbereturnedbyhshifkeydidnotexistinhsh.SeealsoHash::newandHash#default=.

h=Hash.new#=>{}

h.default#=>nil

h.default(2)#=>nil

h=Hash.new("cat")#=>{}

h.default#=>"cat"

h.default(2)#=>"cat"

clear→hsh

compare_by_identity→hsh

compare_by_identity?→trueorfalse

default(key=nil)→obj

Page 327: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

h=Hash.new{|h,k|h[k]=k.to_i*10}#=>{}

h.default#=>nil

h.default(2)#=>20

Setsthedefaultvalue,thevaluereturnedforakeythatdoesnotexistinthehash.ItisnotpossibletosetthedefaulttoaProcthatwillbeexecutedoneachkeylookup.

h={"a"=>100,"b"=>200}

h.default="Gofish"

h["a"]#=>100

h["z"]#=>"Gofish"

#Thisdoesn'tdowhatyoumighthope...

h.default=procdo|hash,key|

hash[key]=key+key

end

h[2]#=>#<Proc:0x401b3948@-:6>

h["cat"]#=>#<Proc:0x401b3948@-:6>

IfHash::newwasinvokedwithablock,returnthatblock,otherwisereturnnil.

h=Hash.new{|h,k|h[k]=k*k}#=>{}

p=h.default_proc#=>#<Proc:0x401b3d08@-:1>

a=[]#=>[]

p.call(a,2)

a#=>[nil,nil,4]

Setsthedefaultproctobeexecutedoneachfailedkeylookup.

h.default_proc=procdo|hash,key|

default=obj→obj

default_proc→anObject

default_proc=proc_objornil

Page 328: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

hash[key]=key+key

end

h[2]#=>4

h["cat"]#=>"catcat"

Deletesthekey-valuepairandreturnsthevaluefromhshwhosekeyisequaltokey.Ifthekeyisnotfound,returnsthedefaultvalue.Iftheoptionalcodeblockisgivenandthekeyisnotfound,passinthekeyandreturntheresultofblock.

h={"a"=>100,"b"=>200}

h.delete("a")#=>100

h.delete("z")#=>nil

h.delete("z"){|el|"#{el}notfound"}#=>"znotfound"

Deleteseverykey-valuepairfromhshforwhichblockevaluatestotrue.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

h={"a"=>100,"b"=>200,"c"=>300}

h.delete_if{|key,value|key>="b"}#=>{"a"=>100}

Callsblockonceforeachkeyinhsh,passingthe

delete(key)→valuedelete(key){|key|block}→value

delete_if{|key,value|block}→hshdelete_if→an_enumerator

each{|key,value|block}→hsheach_pair{|key,value|block}→hsheach→an_enumeratoreach_pair→an_enumerator

Page 329: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

key-valuepairasparameters.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

h={"a"=>100,"b"=>200}

h.each{|key,value|puts"#{key}is#{value}"}

produces:

ais100

bis200

Callsblockonceforeachkeyinhsh,passingthekeyasaparameter.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

h={"a"=>100,"b"=>200}

h.each_key{|key|putskey}

produces:

a

b

Callsblockonceforeachkeyinhsh,passingthekey-valuepairasparameters.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

each_key{|key|block}→hsheach_key→an_enumerator

each{|key,value|block}→hsheach_pair{|key,value|block}→hsheach→an_enumeratoreach_pair→an_enumerator

Page 330: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

h={"a"=>100,"b"=>200}

h.each{|key,value|puts"#{key}is#{value}"}

produces:

ais100

bis200

Callsblockonceforeachkeyinhsh,passingthevalueasaparameter.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

h={"a"=>100,"b"=>200}

h.each_value{|value|putsvalue}

produces:

100

200

Returnstrueifhshcontainsnokey-valuepairs.

{}.empty?#=>true

Returnstrueifhashandotherarebothhasheswiththesamecontent.

each_value{|value|block}→hsheach_value→an_enumerator

empty?→trueorfalse

eql?(other)→trueorfalse

fetch(key[,default])→objfetch(key){|key|block}→obj

Page 331: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsavaluefromthehashforthegivenkey.Ifthekeycan'tbefound,thereareseveraloptions:Withnootherarguments,itwillraiseanKeyErrorexception;ifdefaultisgiven,thenthatwillbereturned;iftheoptionalcodeblockisspecified,thenthatwillberunanditsresultreturned.

h={"a"=>100,"b"=>200}

h.fetch("a")#=>100

h.fetch("z","gofish")#=>"gofish"

h.fetch("z"){|el|"gofish,#{el}"}#=>"gofish,z"

Thefollowingexampleshowsthatanexceptionisraisedifthekeyisnotfoundandadefaultvalueisnotsupplied.

h={"a"=>100,"b"=>200}

h.fetch("z")

produces:

prog.rb:2:in`fetch':keynotfound(KeyError)

fromprog.rb:2

Returnsanewarraythatisaone-dimensionalflatteningofthishash.Thatis,foreverykeyorvaluethatisanarray,extractitselementsintothenewarray.UnlikeArray#flatten,thismethoddoesnotflattenrecursivelybydefault.Theoptionallevelargumentdeterminesthelevelofrecursiontoflatten.

a={1=>"one",2=>[2,"two"],3=>"three"}

a.flatten#=>[1,"one",2,[2,"two"],3,"three"]

a.flatten(2)#=>[1,"one",2,2,"two",3,"three"]

flatten→an_arrayflatten(level)→an_array

Page 332: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthegivenkeyispresentinhsh.

h={"a"=>100,"b"=>200}

h.has_key?("a")#=>true

h.has_key?("z")#=>false

Returnstrueifthegivenvalueispresentforsomekeyinhsh.

h={"a"=>100,"b"=>200}

h.has_value?(100)#=>true

h.has_value?(999)#=>false

Computeahash-codeforthishash.Twohasheswiththesamecontentwillhavethesamehashcode(andwillcompareusingeql?).

SeealsoObject#hash.

Returnstrueifthegivenkeyispresentinhsh.

h={"a"=>100,"b"=>200}

h.has_key?("a")#=>true

has_key?(key)→trueorfalseinclude?(key)→trueorfalsekey?(key)→trueorfalsemember?(key)→trueorfalse

has_value?(value)→trueorfalsevalue?(value)→trueorfalse

hash→fixnum

has_key?(key)→trueorfalseinclude?(key)→trueorfalsekey?(key)→trueorfalsemember?(key)→trueorfalse

Page 333: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

h.has_key?("z")#=>false

Returnthecontentsofthishashasastring.

h={"c"=>300,"a"=>100,"d"=>400,"c"=>300}

h.to_s#=>"{\"c\"=>300,\"a\"=>100,\"d\"=>400}"

Alsoaliasedas:to_s

Returnsanewhashcreatedbyusinghsh'svaluesaskeys,andthekeysasvalues.

h={"n"=>100,"m"=>100,"y"=>300,"d"=>200,

h.invert#=>{0=>"a",100=>"m",200=>"d",300=>"y"}

Deleteseverykey-valuepairfromhshforwhichblockevaluatestofalse.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

Returnsthekeyofanoccurrenceofagivenvalue.Ifthevalueisnotfound,returnsnil.

h={"a"=>100,"b"=>200,"c"=>300,"d"=>300}

h.key(200)#=>"b"

h.key(300)#=>"c"

h.key(999)#=>nil

to_s→stringinspect→string

invert→new_hash

keep_if{|key,value|block}→hshkeep_if→an_enumerator

key(value)→key

Page 334: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthegivenkeyispresentinhsh.

h={"a"=>100,"b"=>200}

h.has_key?("a")#=>true

h.has_key?("z")#=>false

Returnsanewarraypopulatedwiththekeysfromthishash.SeealsoHash#values.

h={"a"=>100,"b"=>200,"c"=>300,"d"=>400}

h.keys#=>["a","b","c","d"]

Returnsthenumberofkey-valuepairsinthehash.

h={"d"=>100,"a"=>200,"v"=>300,"e"=>400}

h.length#=>4

h.delete("a")#=>200

h.length#=>3

Returnstrueifthegivenkeyispresentinhsh.

has_key?(key)→trueorfalseinclude?(key)→trueorfalsekey?(key)→trueorfalsemember?(key)→trueorfalse

keys→array

length→fixnumsize→fixnum

has_key?(key)→trueorfalseinclude?(key)→trueorfalsekey?(key)→trueorfalsemember?(key)→trueorfalse

Page 335: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

h={"a"=>100,"b"=>200}

h.has_key?("a")#=>true

h.has_key?("z")#=>false

Returnsanewhashcontainingthecontentsofother_hashandthecontentsofhsh.Ifnoblockisspecified,thevalueforentrieswithduplicatekeyswillbethatofother_hash.Otherwisethevalueforeachduplicatekeyisdeterminedbycallingtheblockwiththekey,itsvalueinhshanditsvalueinother_hash.

h1={"a"=>100,"b"=>200}

h2={"b"=>254,"c"=>300}

h1.merge(h2)#=>{"a"=>100,"b"=>254,"c"=>300}

h1.merge(h2){|key,oldval,newval|newval-oldval}

#=>{"a"=>100,"b"=>54,"c"=>300}

h1#=>{"a"=>100,"b"=>200}

Addsthecontentsofother_hashtohsh.Ifnoblockisspecified,entrieswithduplicatekeysareoverwrittenwiththevaluesfromother_hash,otherwisethevalueofeachduplicatekeyisdeterminedbycallingtheblockwiththekey,itsvalueinhshanditsvalueinother_hash.

h1={"a"=>100,"b"=>200}

merge(other_hash)→new_hashmerge(other_hash){|key,oldval,newval|block}→new_hash

merge!(other_hash)→hshupdate(other_hash)→hshmerge!(other_hash){|key,oldval,newval|block}→hshupdate(other_hash){|key,oldval,newval|block}→hsh

Page 336: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

h2={"b"=>254,"c"=>300}

h1.merge!(h2)#=>{"a"=>100,"b"=>254,"c"=>300}

h1={"a"=>100,"b"=>200}

h2={"b"=>254,"c"=>300}

h1.merge!(h2){|key,v1,v2|v1}

#=>{"a"=>100,"b"=>200,"c"=>300}

Searchesthroughthehashcomparingobjwiththevalueusing==.Returnsthefirstkey-valuepair(two-elementarray)thatmatches.SeealsoArray#rassoc.

a={1=>"one",2=>"two",3=>"three","ii"=>"two"

a.rassoc("two")#=>[2,"two"]

a.rassoc("four")#=>nil

Rebuildsthehashbasedonthecurrenthashvaluesforeachkey.Ifvaluesofkeyobjectshavechangedsincetheywereinserted,thismethodwillreindexhsh.IfHash#rehashiscalledwhileaniteratoristraversingthehash,anRuntimeErrorwillberaisedintheiterator.

a=["a","b"]

c=["c","d"]

h={a=>100,c=>300}

h[a]#=>100

a[0]="z"

h[a]#=>nil

h.rehash#=>{["z","b"]=>100,["c","d"]=>300}

h[a]#=>100

rassoc(obj)→an_arrayornil

rehash→hsh

reject{|key,value|block}→a_hash

Page 337: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanewhashconsistingofentriesforwhichtheblockreturnsfalse.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

h={"a"=>100,"b"=>200,"c"=>300}

h.reject{|k,v|k<"b"}#=>{"b"=>200,"c"=>300}

h.reject{|k,v|v>100}#=>{"a"=>100}

EquivalenttoHash#delete_if,butreturnsnilifnochangesweremade.

Replacesthecontentsofhshwiththecontentsofother_hash.

h={"a"=>100,"b"=>200}

h.replace({"c"=>300,"d"=>400})#=>{"c"=>300,"d"=>400}

Returnsanewhashconsistingofentriesforwhichtheblockreturnstrue.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

h={"a"=>100,"b"=>200,"c"=>300}

h.select{|k,v|k>"a"}#=>{"b"=>200,"c"=>300}

h.select{|k,v|v<200}#=>{"a"=>100}

reject→an_enumerator

reject!{|key,value|block}→hshornilreject!→an_enumerator

replace(other_hash)→hsh

select{|key,value|block}→a_hashselect→an_enumerator

Page 338: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

EquivalenttoHash#keep_if,butreturnsnilifnochangesweremade.

Removesakey-valuepairfromhshandreturnsitasthetwo-itemarray[key,value],orthehash'sdefaultvalueifthehashisempty.

h={1=>"a",2=>"b",3=>"c"}

h.shift#=>[1,"a"]

h#=>{2=>"b",3=>"c"}

Returnsthenumberofkey-valuepairsinthehash.

h={"d"=>100,"a"=>200,"v"=>300,"e"=>400}

h.length#=>4

h.delete("a")#=>200

h.length#=>3

select!{|key,value|block}→hshornilselect!→an_enumerator

shift→anArrayorobj

length→fixnumsize→fixnum

hsh[key]=value→valuestore(key,value)→value

Page 339: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Associatesthevaluegivenbyvaluewiththekeygivenbykey.

h={"a"=>100,"b"=>200}

h["a"]=9

h["c"]=4

h#=>{"a"=>9,"b"=>200,"c"=>4}

h.store("d",42)#=>42

h#=>{"a"=>9,"b"=>200,"c"=>4,"d"=>42}

keyshouldnothaveitsvaluechangedwhileitisinuseasakey(anunfrozenStringpassedasakeywillbeduplicatedandfrozen).

a="a"

b="b".freeze

h={a=>100,b=>200}

h.key(100).equal?a#=>false

h.key(200).equal?b#=>true

Convertshshtoanestedarrayof[key,value]arrays.

h={"c"=>300,"a"=>100,"d"=>400,"c"=>300}

h.to_a#=>[["c",300],["a",100],["d",400]]

Returnsself.IfcalledonasubclassofHash,convertsthereceivertoaHashobject.

ElementAssignment

to_a→array

to_h→hshornew_hash

Page 340: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsself.

Aliasfor:inspect

Addsthecontentsofother_hashtohsh.Ifnoblockisspecified,entrieswithduplicatekeysareoverwrittenwiththevaluesfromother_hash,otherwisethevalueofeachduplicatekeyisdeterminedbycallingtheblockwiththekey,itsvalueinhshanditsvalueinother_hash.

h1={"a"=>100,"b"=>200}

h2={"b"=>254,"c"=>300}

h1.merge!(h2)#=>{"a"=>100,"b"=>254,"c"=>300}

h1={"a"=>100,"b"=>200}

h2={"b"=>254,"c"=>300}

h1.merge!(h2){|key,v1,v2|v1}

#=>{"a"=>100,"b"=>200,"c"=>300}

Returnstrueifthegivenvalueispresentforsomekeyinhsh.

h={"a"=>100,"b"=>200}

to_hash→hsh

to_s()

merge!(other_hash)→hshupdate(other_hash)→hshmerge!(other_hash){|key,oldval,newval|block}→hshupdate(other_hash){|key,oldval,newval|block}→hsh

has_value?(value)→trueorfalsevalue?(value)→trueorfalse

Page 341: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

h.has_value?(100)#=>true

h.has_value?(999)#=>false

Returnsanewarraypopulatedwiththevaluesfromhsh.SeealsoHash#keys.

h={"a"=>100,"b"=>200,"c"=>300}

h.values#=>[100,200,300]

Returnanarraycontainingthevaluesassociatedwiththegivenkeys.AlsoseeHash.select.

h={"cat"=>"feline","dog"=>"canine","cow"=>"bovine"

h.values_at("cow","cat")#=>["bovine","feline"]

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

values→array

values_at(key,...)→array

Page 342: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIOTheIOclassisthebasisforallinputandoutputinRuby.AnI/Ostreammaybeduplexed(thatis,bidirectional),andsomayusemorethanonenativeoperatingsystemstream.

ManyoftheexamplesinthissectionusetheFileclass,theonlystandardsubclassofIO.Thetwoclassesarecloselyassociated.LiketheFileclass,theSocketlibrarysubclassesfromIO(suchasTCPSocketorUDPSocket).

TheKernel#openmethodcancreateanIO(orFile)objectforthesetypesofarguments:

Aplainstringrepresentsafilenamesuitablefortheunderlyingoperatingsystem.Astringstartingwith"|"indicatesasubprocess.Theremainderofthestringfollowingthe"|"isinvokedasaprocesswithappropriateinput/outputchannelsconnectedtoit.Astringequalto"|-"willcreateanotherRubyinstanceasasubprocess.

TheIOmaybeopenedwithdifferentfilemodes(read-only,write-only)andencodingsforproperconversion.See::newfortheseoptions.SeeKernel#openfordetailsofthevariouscommand

Page 343: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

formatsdescribedabove.

::popen,theOpen3library,orProcess#spawnmayalsobeusedtocommunicatewithsubprocessesthroughanIO.

Rubywillconvertpathnamesbetweendifferentoperatingsystemconventionsifpossible.Forinstance,onaWindowssystemthefilename"/gumby/ruby/test.rb"willbeopenedas"\gumby\ruby\test.rb".WhenspecifyingaWindows-stylefilenameinaRubystring,remembertoescapethebackslashes:

"c:\\gumby\\ruby\\test.rb"

OurexamplesherewillusetheUnix-styleforwardslashes;File::ALT_SEPARATORcanbeusedtogettheplatform-specificseparatorcharacter.

TheglobalconstantARGF(alsoaccessibleas$<)providesanIO-likestreamwhichallowsaccesstoallfilesmentionedonthecommandline(orSTDINifnofilesarementioned).ARGF#pathanditsaliasARGF#filenameareprovidedtoaccessthenameofthefilecurrentlybeingread.

Page 344: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

io/console

Theio/consoleextensionprovidesmethodsforinteractingwiththeconsole.TheconsolecanbeaccessedfromIO.consoleorthestandardinput/output/errorIOobjects.

Requiringio/consoleaddsthefollowingmethods:

IO::consoleIO#rawIO#raw!IO#cookedIO#cooked!IO#getchIO#echo=IO#echo?IO#noechoIO#winsizeIO#winsize=IO#iflushIO#ioflushIO#oflush

Example:

require'io/console'

rows,columns=$stdin.winsize

puts"Yourscreenis#{columns}wideand#{rows}tall"

Page 345: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

InFilesfile.cio.c

ParentObject

IncludedModulesFile::ConstantsEnumerable

Constants

EWOULDBLOCKWaitReadable

EAGAINWaitReadable

EWOULDBLOCKWaitWritable

EAGAINWaitWritable

SEEK_CUR

SetI/Opositionfromthecurrentposition

SEEK_DATA

SetI/Opositiontothenextlocationcontainingdata

SEEK_END

Page 346: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SetI/Opositionfromtheend

SEEK_HOLE

SetI/Opositiontothenexthole

SEEK_SET

SetI/Opositionfromthebeginning

PublicClassMethods

Opensthefile,optionallyseekstothegivenoffset,thenreturnslengthbytes(defaultingtotherestofthefile).binreadensuresthefileisclosedbeforereturning.Theopenmodewouldbe“rb:ASCII-8BIT”.

IO.binread("testfile")#=>"Thisislineone\nThisislinetwo\nThisislinethree\nAndsoon...\n"

IO.binread("testfile",20)#=>"Thisislineone\nThi"

IO.binread("testfile",20,10)#=>"neone\nThisisline"

SameasIO.writeexceptopeningthefileinbinarymodeandASCII-8BITencoding(“wb:ASCII-8BIT”).

::copy_streamcopiessrctodst.srcanddstiseither

binread(name,[length[,offset]])→string

binwrite(name,string,[offset])→fixnumbinwrite(name,string,[offset],open_args)→fixnum

copy_stream(src,dst)copy_stream(src,dst,copy_length)copy_stream(src,dst,copy_length,src_offset)

Page 347: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

afilenameoranIO.

Thismethodreturnsthenumberofbytescopied.

Ifoptionalargumentsarenotgiven,thestartpositionofthecopyisthebeginningofthefilenameorthecurrentfileoffsetoftheIO.Theendpositionofthecopyistheendoffile.

Ifcopy_lengthisgiven,Nomorethancopy_lengthbytesarecopied.

Ifsrc_offsetisgiven,itspecifiesthestartpositionofthecopy.

Whensrc_offsetisspecifiedandsrcisanIO,::copy_streamdoesn'tmovethecurrentfileoffset.

SynonymforIO.new.

ExecutestheblockforeverylineinthenamedI/Oport,wherelinesareseparatedbysep.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

IO.foreach("testfile"){|x|print"GOT",x}

produces:

GOTThisislineone

for_fd(fd,mode[,opt])→io

foreach(name,sep=$/[,open_args]){|line|block}→nilforeach(name,limit[,open_args]){|line|block}→nilforeach(name,sep,limit[,open_args]){|line|block}→nilforeach(...)→an_enumerator

Page 348: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GOTThisislinetwo

GOTThisislinethree

GOTAndsoon...

Ifthelastargumentisahash,it'sthekeywordargumenttoopen.SeeIO.readfordetail.

ReturnsanewIOobject(astream)forthegivenintegerfiledescriptorfdandmodestring.optmaybeusedtospecifypartsofmodeinamorereadablefashion.Seealso::sysopenand::for_fd.

::newiscalledbyvariousFileandIOopeningmethodssuchas::open,Kernel#open,andFile.open.

OpenModeWhenmodeisanintegeritmustbecombinationofthemodesdefinedinFile::Constants(+File::RDONLY+,+File::WRONLY|File::CREAT+).Seetheopen(2)manpageformoreinformation.

Whenmodeisastringitmustbeinoneofthefollowingforms:

fmode

fmode":"ext_enc

fmode":"ext_enc":"int_enc

fmode":""BOM|UTF-*"

fmodeisanIOopenmodestring,ext_encistheexternalencodingfortheIOandint_encistheinternalencoding.

IOOpenModeRubyallowsthefollowingopenmodes:

"r"Read-only,startsatbeginningoffile(defaultmode).

new(fd[,mode][,opt])→io

Page 349: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

"r+"Read-write,startsatbeginningoffile.

"w"Write-only,truncatesexistingfile

tozerolengthorcreatesanewfileforwriting.

"w+"Read-write,truncatesexistingfiletozerolength

orcreatesanewfileforreadingandwriting.

"a"Write-only,eachwritecallappendsdataatendoffile.

Createsanewfileforwritingiffiledoesnotexist.

"a+"Read-write,eachwritecallappendsdataatendoffile.

Createsanewfileforreadingandwritingiffiledoes

notexist.

Thefollowingmodesmustbeusedseparately,andalongwithoneormoreofthemodesseenabove.

"b"Binaryfilemode

SuppressesEOL<->CRLFconversiononWindows.And

setsexternalencodingtoASCII-8BITunlessexplicitly

specified.

"t"Textfilemode

WhentheopenmodeoforiginalIOisreadonly,themodecannotbechangedtobewritable.Similarly,theopenmodecannotbechangedfromwriteonlytoreadable.

Whensuchachangeisattemptedtheerrorisraisedindifferentlocationsaccordingtotheplatform.

IOEncodingWhenext_encisspecified,stringsreadwillbetaggedbytheencodingwhenreading,andstringsoutputwillbeconvertedtothespecifiedencodingwhenwriting.

Whenext_encandint_encarespecifiedreadstringswillbeconvertedfromext_enctoint_encuponinput,andwrittenstringswillbeconvertedfromint_encto

Page 350: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ext_encuponoutput.SeeEncodingforfurtherdetailsoftranscodingoninputandoutput.

If“BOM|UTF-8”,“BOM|UTF-16LE”or“BOM|UTF16-BE”areused,rubychecksforaUnicodeBOMintheinputdocumenttohelpdeterminetheencoding.ForUTF-16encodingsthefileopenmodemustbebinary.Whenpresent,theBOMisstrippedandtheexternalencodingfromtheBOMisused.WhentheBOMismissingthegivenUnicodeencodingisusedasext_enc.(TheBOM-setencodingoptioniscaseinsensitive,so“bom|utf-8”isalsovalid.)

Optionsoptcanbeusedinsteadofmodeforimprovedreadability.Thefollowingkeysaresupported:

:modeSameasmodeparameter

:external_encodingExternalencodingfortheIO.“-”isasynonymforthedefaultexternalencoding.

:internal_encodingInternalencodingfortheIO.“-”isasynonymforthedefaultinternalencoding.

Ifthevalueisnilnoconversionoccurs.

:encodingSpecifiesexternalandinternalencodingsas“extern:intern”.

:textmodeIfthevalueistruthvalue,sameas“t”inargumentmode.

:binmodeIfthevalueistruthvalue,sameas“b”inargument

Page 351: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

mode.

:autocloseIfthevalueisfalse,thefdwillbekeptopenafterthisIOinstancegetsfinalized.

Also,optcanhavesamekeysinString#encodeforcontrollingconversionbetweentheexternalencodingandtheinternalencoding.

Example1fd=IO.sysopen("/dev/tty","w")

a=IO.new(fd,"w")

$stderr.puts"Hello"

a.puts"World"

Produces:

Hello

World

Example2require'fcntl'

fd=STDERR.fcntl(Fcntl::F_DUPFD)

io=IO.new(fd,mode:'w:UTF-16LE',cr_newline:true)

io.puts"Hello,World!"

fd=STDERR.fcntl(Fcntl::F_DUPFD)

io=IO.new(fd,mode:'w',cr_newline:true,

external_encoding:Encoding::UTF_16LE)

io.puts"Hello,World!"

Bothofaboveprint“Hello,World!”inUTF-16LEtostandarderroroutputwithconvertingEOLgeneratedbyputstoCR.

Page 352: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Withnoassociatedblock,IO.openisasynonymfor::new.Iftheoptionalcodeblockisgiven,itwillbepassedioasanargument,andtheIOobjectwillautomaticallybeclosedwhentheblockterminates.Inthisinstance,::openreturnsthevalueoftheblock.

See::newforadescriptionofthefd,modeandoptparameters.

Createsapairofpipeendpoints(connectedtoeachother)andreturnsthemasatwo-elementarrayofIOobjects:[read_io,write_io].

Ifablockisgiven,theblockiscalledandreturnsthevalueoftheblock.read_ioandwrite_ioaresenttotheblockasarguments.Ifread_ioandwrite_ioarenotclosedwhentheblockexits,theyareclosed.i.e.closingread_ioand/orwrite_iodoesn'tcauseanerror.

Notavailableonallplatforms.

Ifanencoding(encodingnameorencodingobject)isspecifiedasanoptionalargument,readstringfrompipeistaggedwiththeencodingspecified.Iftheargumentisacolonseparatedtwoencodingnames“A:B”,thereadstringisconvertedfromencodingA

open(fd,mode="r"[,opt])→ioopen(fd,mode="r"[,opt]){|io|block}→obj

pipe→[read_io,write_io]pipe(ext_enc)→[read_io,write_io]pipe("ext_enc:int_enc"[,opt])→[read_io,write_io]pipe(ext_enc,int_enc[,opt])→[read_io,write_io]pipe(...){|read_io,write_io|...}

Page 353: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(externalencoding)toencodingB(internalencoding),thentaggedwithB.Iftwooptionalargumentsarespecified,thosemustbeencodingobjectsorencodingnames,andthefirstoneistheexternalencoding,andthesecondoneistheinternalencoding.Iftheexternalencodingandtheinternalencodingisspecified,optionalhashargumentspecifytheconversionoption.

Intheexamplebelow,thetwoprocessesclosetheendsofthepipethattheyarenotusing.Thisisnotjustacosmeticnicety.Thereadendofapipewillnotgenerateanendoffileconditionifthereareanywriterswiththepipestillopen.Inthecaseoftheparentprocess,therd.readwillneverreturnifitdoesnotfirstissueawr.close.

rd,wr=IO.pipe

iffork

wr.close

puts"Parentgot:<#{rd.read}>"

rd.close

Process.wait

else

rd.close

puts"Sendingmessagetoparent"

wr.write"HiDad"

wr.close

end

produces:

Sendingmessagetoparent

Parentgot:<HiDad>

Runsthespecifiedcommandasasubprocess;the

popen([env,]cmd,mode="r"[,opt])→iopopen([env,]cmd,mode="r"[,opt]){|io|block}→obj

Page 354: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

subprocess'sstandardinputandoutputwillbeconnectedtothereturnedIOobject.

ThePIDofthestartedprocesscanbeobtainedby#pidmethod.

cmdisastringoranarrayasfollows.

cmd:

"-":fork

commandline:commandlinestringwhichispassedtoashell

[env,cmdname,arg1,...,opts]:commandnameandzeroormorearguments(noshell)

[env,[cmdname,argv0],arg1,...,opts]:commandname,argv[0]andzeroormorearguments(noshell)

(envandoptsareoptional.)

IfcmdisaString“-'',thenanewinstanceofRubyisstartedasthesubprocess.

IfcmdisanArrayofString,thenitwillbeusedasthesubprocess'sargvbypassingashell.Thearraycancontainsahashatfirstforenvironmentsandahashatlastforoptionssimilartospawn.

Thedefaultmodeforthenewfileobjectis“r'',butmodemaybesettoanyofthemodeslistedinthedescriptionforclassIO.Thelastargumentoptqualifiesmode.

#setIOencoding

IO.popen("nkf-efilename",:external_encoding=>"EUC-JP"

euc_jp_string=nkf_io.read

}

#mergestandardoutputandstandarderrorusing

#spawnoption.SeethedocumentofKernel.spawn.

IO.popen(["ls","/",:err=>[:child,:out]]){|ls_io|

ls_result_with_error=ls_io.read

}

#spawnoptionscanbemixedwithIOoptions

IO.popen(["ls","/"],:err=>[:child,:out]){|ls_io|

ls_result_with_error=ls_io.read

}

Page 355: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

RaisesexceptionswhichIO.pipeandKernel.spawnraise.

Ifablockisgiven,RubywillrunthecommandasachildconnectedtoRubywithapipe.Ruby'sendofthepipewillbepassedasaparametertotheblock.Attheendofblock,Rubyclosesthepipeandsets$?.InthiscaseIO.popenreturnsthevalueoftheblock.

Ifablockisgivenwithacmdof“-'',theblockwillberunintwoseparateprocesses:onceintheparent,andonceinachild.Theparentprocesswillbepassedthepipeobjectasaparametertotheblock,thechildversionoftheblockwillbepassednil,andthechild'sstandardinandstandardoutwillbeconnectedtotheparentthroughthepipe.Notavailableonallplatforms.

f=IO.popen("uname")

pf.readlines

f.close

puts"Parentis#{Process.pid}"

IO.popen("date"){|f|putsf.gets}

IO.popen("-"){|f|$stderr.puts"#{Process.pid}ishere,fis#{f.inspect}"

p$?

IO.popen(%wsed-es|^|<foo>|-es&$&;zot;&","r+"){|f

f.puts"bar";f.close_write;putsf.gets

}

produces:

["Linux\n"]

Parentis21346

ThuJan1522:41:19JST2009

21346ishere,fis#<IO:fd3>

21352ishere,fisnil

#<Process::Status:pid21352exit0>

<foo>bar;zot;

Page 356: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Opensthefile,optionallyseekstothegivenoffset,thenreturnslengthbytes(defaultingtotherestofthefile).readensuresthefileisclosedbeforereturning.

OptionsTheoptionshashacceptsthefollowingkeys:

encodingstringorencoding

Specifiestheencodingofthereadstring.encoding:willbeignorediflengthisspecified.SeeEncoding.aliasesforpossibleencodings.

modestring

Specifiesthemodeargumentforopen().Itmuststartwithan“r”otherwiseitwillcauseanerror.See::newforthelistofpossiblemodes.

open_argsarrayofstrings

Specifiesargumentsforopen()asanarray.Thiskeycannotbeusedincombinationwitheitherencoding:ormode:.

Examples:

IO.read("testfile")#=>"Thisislineone\nThisislinetwo\nThisislinethree\nAndsoon...\n"

IO.read("testfile",20)#=>"Thisislineone\nThi"

IO.read("testfile",20,10)#=>"neone\nThisisline"

IO.read("binfile",mode:"rb")#=>"\xF7\x00\x00\x0E\x12"

read(name,[length[,offset]][,opt])→string

readlines(name,sep=$/[,open_args])→

Page 357: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Readstheentirefilespecifiedbynameasindividuallines,andreturnsthoselinesinanarray.Linesareseparatedbysep.

a=IO.readlines("testfile")

a[0]#=>"Thisislineone\n"

Ifthelastargumentisahash,it'sthekeywordargumenttoopen.SeeIO.readfordetail.

Callsselect(2)systemcall.ItmonitorsgivenarraysofIOobjects,waitsoneormoreofIOobjectsreadyforreading,arereadyforwriting,andhavependingexceptionsrespectively,andreturnsanarraythatcontainsarraysofthoseIOobjects.ItwillreturnnilifoptionaltimeoutvalueisgivenandnoIOobjectisreadyintimeoutseconds.

IO.selectpeeksthebufferofIOobjectsfortestingreadability.IftheIObufferisnotempty,IO.selectimmediatelynotifyreadability.This“peek”isonlyhappenforIOobjects.ItisnothappenforIO-likeobjectssuchasOpenSSL::SSL::SSLSocket.

ThebestwaytouseIO.selectisinvokingitafternonblockingmethodssuchasread_nonblock,write_nonblock,etc.ThemethodsraisesanexceptionwhichisextendedbyIO::WaitReadableor

arrayreadlines(name,limit[,open_args])→arrayreadlines(name,sep,limit[,open_args])→array

select(read_array[,write_array[,error_array[,timeout]]])→arrayornil

Page 358: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

IO::WaitWritable.ThemodulesnotifyhowthecallershouldwaitwithIO.select.IfIO::WaitReadableisraised,thecallershouldwaitforreading.IfIO::WaitWritableisraised,thecallershouldwaitforwriting.

So,blockingread(readpartial)canbeemulatedusingread_nonblockandIO.selectasfollows:

begin

result=io_like.read_nonblock(maxlen)

rescueIO::WaitReadable

IO.select([io_like])

retry

rescueIO::WaitWritable

IO.select(nil,[io_like])

retry

end

Especially,thecombinationofnonblockingmethodsandIO.selectispreferredforIOlikeobjectssuchasOpenSSL::SSL::SSLSocket.Ithasto_iomethodtoreturnunderlyingIOobject.IO.selectcallsto_iotoobtainthefiledescriptortowait.

ThismeansthatreadabilitynotifiedbyIO.selectdoesn'tmeanreadabilityfromOpenSSL::SSL::SSLSocketobject.

MostpossiblesituationisOpenSSL::SSL::SSLSocketbufferssomedata.IO.selectdoesn'tseethebuffer.SoIO.selectcanblockwhenOpenSSL::SSL::SSLSocket#readpartialdoesn'tblock.

Howeverseveralmorecomplicatedsituationexists.

SSLisaprotocolwhichissequenceofrecords.Therecordconsistsmultiplebytes.So,theremotesideofSSLsendsapartialrecord,IO.selectnotifiesreadabilitybutOpenSSL::SSL::SSLSocketcannot

Page 359: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

decryptabyteandOpenSSL::SSL::SSLSocket#readpartialwillblocks.

Also,theremotesidecanrequestSSLrenegotiationwhichforcesthelocalSSLenginewritessomedata.ThismeansOpenSSL::SSL::SSLSocket#readpartialmayinvokewritesystemcallanditcanblock.Insuchsituation,OpenSSL::SSL::SSLSocket#read_nonblockraisesIO::WaitWritableinsteadofblocking.So,thecallershouldwaitforreadyforwritabilityasaboveexample.

ThecombinationofnonblockingmethodsandIO.selectisalsousefulforstreamssuchastty,pipesocketsocketwhenmultipleprocessreadformastream.

Finally,Linuxkerneldevelopersdoesn'tguaranteethatreadabilityofselect(2)meansreadabilityoffollowingread(2)evenforsingleprocess.Seeselect(2)manualonGNU/Linuxsystem.

InvokingIO.selectbeforeIO#readpartialworkswellinusual.HoweveritisnotthebestwaytouseIO.select.

Thewritabilitynotifiedbyselect(2)doesn'tshowhowmanybyteswritable.IO#writemethodblocksuntilgivenwholestringiswritten.So,IO#write(twoormorebytes)canblockafterwritabilityisnotifiedbyIO.select.IO#write_nonblockisrequiredtoavoidtheblocking.

Blockingwrite(write)canbeemulatedusingwrite_nonblockandIO.selectasfollows:IO::WaitReadableshouldalsoberescuedforSSLrenegotiationinOpenSSL::SSL::SSLSocket.

while0<string.bytesize

Page 360: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

begin

written=io_like.write_nonblock(string)

rescueIO::WaitReadable

IO.select([io_like])

retry

rescueIO::WaitWritable

IO.select(nil,[io_like])

retry

end

string=string.byteslice(written..-1)

end

Parametersread_arrayanarrayofIOobjectsthatwaituntilreadyforread

write_arrayanarrayofIOobjectsthatwaituntilreadyforwrite

error_arrayanarrayofIOobjectsthatwaitforexceptions

timeoutanumericvalueinsecond

Examplerp,wp=IO.pipe

mesg="ping"

100.times{

#IO.selectfollowsIO#read.NotthebestwaytouseIO.select.

rs,ws,=IO.select([rp],[wp])

ifr=rs[0]

ret=r.read(5)

printret

caseret

when/ping/

mesg="pong\n"

when/pong/

mesg="ping"

end

end

Page 361: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ifw=ws[0]

w.write(mesg)

end

}

produces:

pingpong

pingpong

pingpong

(snipped)

ping

Opensthegivenpath,returningtheunderlyingfiledescriptorasaFixnum.

IO.sysopen("testfile")#=>3

TrytoconvertobjintoanIO,using#to_iomethod.ReturnsconvertedIOornilifobjcannotbeconvertedforanyreason.

IO.try_convert(STDOUT)#=>STDOUT

IO.try_convert("STDOUT")#=>nil

require'zlib'

f=open("/tmp/zz.gz")#=>#<File:/tmp/zz.gz>

z=Zlib::GzipReader.open(f)#=>#<Zlib::GzipReader:0x81d8744>

IO.try_convert(z)#=>#<File:/tmp/zz.gz>

Opensthefile,optionallyseekstothegivenoffset,

sysopen(path,[mode,[perm]])→fixnum

try_convert(obj)→ioornil

write(name,string,[offset])→fixnumwrite(name,string,[offset],open_args)→fixnum

Page 362: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

writesstring,thenreturnsthelengthwritten.writeensuresthefileisclosedbeforereturning.Ifoffsetisnotgiven,thefileistruncated.Otherwise,itisnottruncated.

Ifthelastargumentisahash,itspecifiesoptionforinternalopen().Thekeywouldbethefollowing.open_args:isexclusivetoothers.

encoding:stringorencoding

specifiesencodingofthereadstring.encodingwill

iflengthisspecified.

mode:string

specifiesmodeargumentforopen().itshouldstart

otherwiseitwouldcauseerror.

perm:fixnum

specifiespermargumentforopen().

open_args:array

specifiesargumentsforopen()asanarray.

IO.write("testfile","0123456789",20)#=>10

#Filecouldcontain:"Thisislineone\nThi0123456789two\nThisislinethree\nAndsoon...\n"

IO.write("testfile","0123456789")#=>10

#Filewouldnowread:"0123456789"

PublicInstanceMethods

StringOutput—Writesobjtoios.objwillbeconvertedtoastringusingto_s.

$stdout<<"Hello"<<"world!\n"

ios<<obj→ios

Page 363: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

produces:

Helloworld!

Announceanintentiontoaccessdatafromthecurrentfileinaspecificpattern.Onplatformsthatdonotsupporttheposix_fadvise(2)systemcall,thismethodisano-op.

adviceisoneofthefollowingsymbols:

:normalNoadvicetogive;thedefaultassumptionforanopenfile.

:sequentialThedatawillbeaccessedsequentiallywithloweroffsetsreadbeforehigherones.

:randomThedatawillbeaccessedinrandomorder.

:willneedThedatawillbeaccessedinthenearfuture.

:dontneedThedatawillnotbeaccessedinthenearfuture.

:noreuseThedatawillonlybeaccessedonce.

Thesemanticsofapieceofadviceareplatform-dependent.Seeman2posix_fadvisefordetails.

“data”meanstheregionofthecurrentfilethatbeginsatoffsetandextendsforlenbytes.Iflenis0,theregionendsatthelastbyteofthefile.Bydefault,bothoffsetandlenare0,meaningthattheadviceappliestotheentirefile.

advise(advice,offset=0,len=0)→nil

Page 364: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ifanerroroccurs,oneofthefollowingexceptionswillberaised:IOError

TheIOstreamisclosed.

Errno::EBADF

Thefiledescriptorofthecurrentfileisinvalid.

Errno::EINVAL

Aninvalidvalueforadvicewasgiven.

Errno::ESPIPE

ThefiledescriptorofthecurrentfilereferstoaFIFOorpipe.(LinuxraisesErrno::EINVALinthiscase).

TypeError

EitheradvicewasnotaSymbol,oroneoftheotherargumentswasnotanInteger.

RangeError

Oneoftheargumentsgivenwastoobig/small.

Thislistisnotexhaustive;otherErrnoexceptionsarealsopossible.

Setsauto-closeflag.

f=open("/dev/null")

IO.for_fd(f.fileno)

#...

f.gets#maycauseIOError

f=open("/dev/null")

IO.for_fd(f.fileno).autoclose=true

#...

f.gets#won'tcauseIOError

autoclose=bool→trueorfalse

autoclose?→trueorfalse

Page 365: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueiftheunderlyingfiledescriptorofioswillbeclosedautomaticallyatitsfinalization,otherwisefalse.

Putsiosintobinarymode.Onceastreamisinbinarymode,itcannotberesettononbinarymode.

newlineconversiondisabled

encodingconversiondisabled

contentistreatedasASCII-8BIT

Returnstrueifiosisbinmode.

Thisisadeprecatedaliasforeach_byte.

Thisisadeprecatedaliasforeach_char.

Closesiosandflushesanypendingwritestotheoperatingsystem.Thestreamisunavailableforanyfurtherdataoperations;anIOErrorisraisedifsuchanattemptismade.I/Ostreamsareautomaticallyclosedwhentheyareclaimedbythegarbagecollector.

IfiosisopenedbyIO.popen,closesets$?.

binmode→ios

binmode?→trueorfalse

bytes()

chars()

close→nil

Page 366: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Setsaclose-on-execflag.

f=open("/dev/null")

f.close_on_exec=true

system("cat","/proc/self/fd/#{f.fileno}")#cat:/proc/self/fd/3:Nosuchfileordirectory

f.closed?#=>false

Rubysetsclose-on-execflagsofallfiledescriptorsbydefaultsinceRuby2.0.0.Soyoudon'tneedtosetbyyourself.Also,unsettingaclose-on-execflagcancausefiledescriptorleakifanotherthreadusefork()andexec()(viasystem()methodforexample).Ifyoureallyneedsfiledescriptorinheritancetochildprocess,usespawn()'sargumentsuchasfd=>fd.

Returnstrueifioswillbeclosedonexec.

f=open("/dev/null")

f.close_on_exec?#=>false

f.close_on_exec=true

f.close_on_exec?#=>true

f.close_on_exec=false

f.close_on_exec?#=>false

ClosesthereadendofaduplexI/Ostream(i.e.,onethatcontainsbothareadandawritestream,suchasapipe).WillraiseanIOErrorifthestreamisnotduplexed.

f=IO.popen("/bin/sh","r+")

f.close_read

f.readlines

produces:

close_on_exec=bool→trueorfalse

close_on_exec?→trueorfalse

close_read→nil

Page 367: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

prog.rb:3:in`readlines':notopenedforreading(IOError)

fromprog.rb:3

ClosesthewriteendofaduplexI/Ostream(i.e.,onethatcontainsbothareadandawritestream,suchasapipe).WillraiseanIOErrorifthestreamisnotduplexed.

f=IO.popen("/bin/sh","r+")

f.close_write

f.print"nowhere"

produces:

prog.rb:3:in`write':notopenedforwriting(IOError)

fromprog.rb:3:in`print'

fromprog.rb:3

Returnstrueifiosiscompletelyclosed(forduplexstreams,bothreaderandwriter),falseotherwise.

f=File.new("testfile")

f.close#=>nil

f.closed?#=>true

f=IO.popen("/bin/sh","r+")

f.close_write#=>nil

f.closed?#=>false

f.close_read#=>nil

f.closed?#=>true

Thisisadeprecatedaliasforeach_codepoint.

close_write→nil

closed?→trueorfalse

codepoints()

Page 368: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Executestheblockforeverylineinios,wherelinesareseparatedbysep.iosmustbeopenedforreadingoranIOErrorwillberaised.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

f=File.new("testfile")

f.each{|line|puts"#{f.lineno}:#{line}"}

produces:

1:Thisislineone

2:Thisislinetwo

3:Thisislinethree

4:Andsoon...

Callsthegivenblockonceforeachbyte(0..255)inios,passingthebyteasanargument.ThestreammustbeopenedforreadingoranIOErrorwillberaised.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

f=File.new("testfile")

checksum=0

each(sep=$/){|line|block}→ioseach(limit){|line|block}→ioseach(sep,limit){|line|block}→ioseach(...)→an_enumeratoreach_line(sep=$/){|line|block}→ioseach_line(limit){|line|block}→ioseach_line(sep,limit){|line|block}→ioseach_line(...)→an_enumerator

each_byte{|byte|block}→ioseach_byte→an_enumerator

Page 369: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

f.each_byte{|x|checksum^=x}#=>#<File:testfile>

checksum#=>12

Callsthegivenblockonceforeachcharacterinios,passingthecharacterasanargument.ThestreammustbeopenedforreadingoranIOErrorwillberaised.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

f=File.new("testfile")

f.each_char{|c|printc,''}#=>#<File:testfile>

PassestheIntegerordinalofeachcharacterinios,passingthecodepointasanargument.ThestreammustbeopenedforreadingoranIOErrorwillberaised.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

each_char{|c|block}→ioseach_char→an_enumerator

each_codepoint{|c|block}→ioscodepoints{|c|block}→ioseach_codepoint→an_enumeratorcodepoints→an_enumerator

each(sep=$/){|line|block}→ioseach(limit){|line|block}→ioseach(sep,limit){|line|block}→ioseach(...)→an_enumeratoreach_line(sep=$/){|line|block}→ios

Page 370: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Executestheblockforeverylineinios,wherelinesareseparatedbysep.iosmustbeopenedforreadingoranIOErrorwillberaised.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

f=File.new("testfile")

f.each{|line|puts"#{f.lineno}:#{line}"}

produces:

1:Thisislineone

2:Thisislinetwo

3:Thisislinethree

4:Andsoon...

Returnstrueifiosisatendoffilethatmeanstherearenomoredatatoread.ThestreammustbeopenedforreadingoranIOErrorwillberaised.

f=File.new("testfile")

dummy=f.readlines

f.eof#=>true

Ifiosisastreamsuchaspipeorsocket,IO#eof?blocksuntiltheotherendsendssomedataorclosesit.

r,w=IO.pipe

Thread.new{sleep1;w.close}

r.eof?#=>trueafter1secondblocking

r,w=IO.pipe

Thread.new{sleep1;w.puts"a"}

each_line(limit){|line|block}→ioseach_line(sep,limit){|line|block}→ioseach_line(...)→an_enumerator

eof→trueorfalseeof?→trueorfalse

Page 371: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

r.eof?#=>falseafter1secondblocking

r,w=IO.pipe

r.eof?#blocksforever

NotethatIO#eof?readsdatatotheinputbytebuffer.SoIO#sysreadmaynotbehaveasyouintendwithIO#eof?,unlessyoucallIO#rewindfirst(whichisnotavailableforsomestreams).

Returnstrueifiosisatendoffilethatmeanstherearenomoredatatoread.ThestreammustbeopenedforreadingoranIOErrorwillberaised.

f=File.new("testfile")

dummy=f.readlines

f.eof#=>true

Ifiosisastreamsuchaspipeorsocket,IO#eof?blocksuntiltheotherendsendssomedataorclosesit.

r,w=IO.pipe

Thread.new{sleep1;w.close}

r.eof?#=>trueafter1secondblocking

r,w=IO.pipe

Thread.new{sleep1;w.puts"a"}

r.eof?#=>falseafter1secondblocking

r,w=IO.pipe

r.eof?#blocksforever

NotethatIO#eof?readsdatatotheinputbytebuffer.SoIO#sysreadmaynotbehaveasyouintendwithIO#eof?,unlessyoucallIO#rewindfirst(whichisnotavailableforsomestreams).

eof→trueorfalseeof?→trueorfalse

Page 372: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstheEncodingobjectthatrepresentstheencodingofthefile.Ifioiswritemodeandnoencodingisspecified,returnsnil.

Providesamechanismforissuinglow-levelcommandstocontrolorqueryfile-orientedI/Ostreams.Argumentsandresultsareplatformdependent.Ifargisanumber,itsvalueispasseddirectly.Ifitisastring,itisinterpretedasabinarysequenceofbytes(Array#packmightbeausefulwaytobuildthisstring).OnUnixplatforms,seefcntl(2)fordetails.Notimplementedonallplatforms.

Immediatelywritesallbuffereddatainiostodisk.

Iftheunderlyingoperatingsystemdoesnotsupportfdatasync(2),IO#fsynciscalledinstead(whichmightraiseaNotImplementedError).

Returnsanintegerrepresentingthenumericfiledescriptorforios.

$stdin.fileno#=>0

$stdout.fileno#=>1

Alsoaliasedas:to_i

Flushesanybuffereddatawithiniostotheunderlying

external_encoding→encoding

fcntl(integer_cmd,arg)→integer

fdatasync→0ornil

fileno→fixnumto_i→fixnum

flush→ios

Page 373: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

operatingsystem(notethatthisisRubyinternalbufferingonly;theOSmaybufferthedataaswell).

$stdout.print"nonewline"

$stdout.flush

produces:

nonewline

Immediatelywritesallbuffereddatainiostodisk.NotethatfsyncdiffersfromusingIO#sync=.ThelatterensuresthatdataisflushedfromRuby'sbuffers,butdoesnotguaranteethattheunderlyingoperatingsystemactuallywritesittodisk.

NotImplementedErrorisraisediftheunderlyingoperatingsystemdoesnotsupportfsync(2).

Getsthenext8-bitbyte(0..255)fromios.Returnsnilifcalledatendoffile.

f=File.new("testfile")

f.getbyte#=>84

f.getbyte#=>104

Readsaone-characterstringfromios.Returnsnilifcalledatendoffile.

f=File.new("testfile")

f.getc#=>"h"

f.getc#=>"e"

fsync→0ornil

getbyte→fixnumornil

getc→stringornil

Page 374: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Readsthenext“line''fromtheI/Ostream;linesareseparatedbysep.Aseparatorofnilreadstheentirecontents,andazero-lengthseparatorreadstheinputaparagraphatatime(twosuccessivenewlinesintheinputseparateparagraphs).ThestreammustbeopenedforreadingoranIOErrorwillberaised.Thelinereadinwillbereturnedandalsoassignedto$_.Returnsnilifcalledatendoffile.Ifthefirstargumentisaninteger,oroptionalsecondargumentisgiven,thereturningstringwouldnotbelongerthanthegivenvalueinbytes.

File.new("testfile").gets#=>"Thisislineone\n"

$_#=>"Thisislineone\n"

ReturnastringdescribingthisIOobject.

ReturnstheEncodingoftheinternalstringifconversionisspecified.Otherwisereturnsnil.

Providesamechanismforissuinglow-levelcommandstocontrolorqueryI/Odevices.Argumentsandresultsareplatformdependent.Ifargisanumber,itsvalueispasseddirectly.Ifitisastring,itisinterpretedasabinarysequenceofbytes.OnUnixplatforms,seeioctl(2)fordetails.Not

gets(sep=$/)→stringornilgets(limit)→stringornilgets(sep,limit)→stringornil

inspect→string

internal_encoding→encoding

ioctl(integer_cmd,arg)→integer

Page 375: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

implementedonallplatforms.

Returnstrueifiosisassociatedwithaterminaldevice(tty),falseotherwise.

File.new("testfile").isatty#=>false

File.new("/dev/tty").isatty#=>true

Returnsthecurrentlinenumberinios.Thestreammustbeopenedforreading.linenocountsthenumberoftimesgetsiscalledratherthanthenumberofnewlinesencountered.Thetwovalueswilldifferifgetsiscalledwithaseparatorotherthannewline.

Methodsthatuse$/likeeach,linesandreadlinewillalsoincrementlineno.

Seealsothe$.variable.

f=File.new("testfile")

f.lineno#=>0

f.gets#=>"Thisislineone\n"

f.lineno#=>1

f.gets#=>"Thisislinetwo\n"

f.lineno#=>2

Manuallysetsthecurrentlinenumbertothegivenvalue.$.isupdatedonlyonthenextread.

f=File.new("testfile")

f.gets#=>"Thisislineone\n"

$.#=>1

f.lineno=1000

isatty→trueorfalsetty?→trueorfalse

lineno→integer

lineno=integer→integer

Page 376: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

f.lineno#=>1000

$.#=>1#linenooflastread

f.gets#=>"Thisislinetwo\n"

$.#=>1001#linenooflastread

Thisisadeprecatedaliasforeach_line.

ReturnstheprocessIDofachildprocessassociatedwithios.ThiswillbesetbyIO.popen.

pipe=IO.popen("-")

ifpipe

$stderr.puts"Inparent,childpidis#{pipe.pid}"

else

$stderr.puts"Inchild,pidis#{$$}"

end

produces:

Inchild,pidis26209

Inparent,childpidis26209

Returnsthecurrentoffset(inbytes)ofios.

f=File.new("testfile")

f.pos#=>0

f.gets#=>"Thisislineone\n"

f.pos#=>17

Seekstothegivenposition(inbytes)inios.Itisnot

lines(*args)

pid→fixnum

pos→integertell→integer

pos=integer→integer

Page 377: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

guaranteedthatseekingtotherightpositionwheniosistextmode.

f=File.new("testfile")

f.pos=17

f.gets#=>"Thisislinetwo\n"

Writesthegivenobject(s)toios.Thestreammustbeopenedforwriting.Iftheoutputfieldseparator($,)isnotnil,itwillbeinsertedbetweeneachobject.Iftheoutputrecordseparator($\</code>)isnot<code>nil,itwillbeappendedtotheoutput.Ifnoargumentsaregiven,prints$_.Objectsthataren'tstringswillbeconvertedbycallingtheirto_smethod.Withnoargument,printsthecontentsofthevariable$_.Returnsnil.

$stdout.print("Thisis",100,"percent.\n")

produces:

Thisis100percent.

Formatsandwritestoios,convertingparametersundercontroloftheformatstring.SeeKernel#sprintffordetails.

IfobjisNumeric,writethecharacterwhosecodeistheleast-significantbyteofobj,otherwisewritethefirstbyteofthestringrepresentationofobjtoios.

print()→nilprint(obj,...)→nil

printf(format_string[,obj,...])→nil

putc(obj)→obj

Page 378: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Note:Thismethodisnotsafeforusewithmulti-bytecharactersasitwilltruncatethem.

$stdout.putc"A"

$stdout.putc65

produces:

AA

WritesthegivenobjectstoiosaswithIO#print.Writesarecordseparator(typicallyanewline)afteranythatdonotalreadyendwithanewlinesequence.Ifcalledwithanarrayargument,writeseachelementonanewline.Ifcalledwithoutarguments,outputsasinglerecordseparator.

$stdout.puts("this","is","a","test")

produces:

this

is

a

test

ReadslengthbytesfromtheI/Ostream.

lengthmustbeanon-negativeintegerornil.

Iflengthisapositiveinteger,ittriestoreadlengthbyteswithoutanyconversion(binarymode).Itreturnsnilorastringwhoselengthis1tolengthbytes.nilmeansitmetEOFatbeginning.The1tolength-1bytesstringmeansitmetEOFafterreading

puts(obj,...)→nil

read([length[,outbuf]])→string,outbuf,ornil

Page 379: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

theresult.Thelengthbytesstringmeansitdoesn'tmeetEOF.TheresultedstringisalwaysASCII-8BITencoding.

Iflengthisomittedorisnil,itreadsuntilEOFandtheencodingconversionisapplied.ItreturnsastringevenifEOFismetatbeginning.

Iflengthiszero,itreturns"".

Iftheoptionaloutbufargumentispresent,itmustreferenceaString,whichwillreceivethedata.Theoutbufwillcontainonlythereceiveddataafterthemethodcallevenifitisnotemptyatthebeginning.

Atendoffile,itreturnsnilor""dependonlength.ios.read()andios.read(nil)returns"".ios.read(positive-integer)returnsnil.

f=File.new("testfile")

f.read(16)#=>"Thisislineone"

#readswholefile

open("file"){|f|

data=f.read#Thisreturnsastringevenifthefileisempty.

...

}

#iterateoverfixedlengthrecords.

open("fixed-record-file"){|f|

whilerecord=f.read(256)

...

end

}

#iterateovervariablelengthrecords.

#recordisprefixedby32-bitlength.

open("variable-record-file"){|f|

whilelen=f.read(4)

len=len.unpack("N")[0]#32-bitlength

record=f.read(len)#Thisreturnsastringeveniflenis0.

end

}

Page 380: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Notethatthismethodbehaveslikefread()functioninC.Thismeansitretrytoinvokeread(2)systemcalltoreaddatawiththespecifiedlength(oruntilEOF).Thisbehaviorispreservedevenifiosisnon-blockingmode.(Thismethodisnon-blockingflaginsensitiveasothermethods.)Ifyouneedthebehaviorlikesingleread(2)systemcall,considerreadpartial,#read_nonblockandsysread.

Readsatmostmaxlenbytesfromiosusingtheread(2)systemcallafterO_NONBLOCKissetfortheunderlyingfiledescriptor.

Iftheoptionaloutbufargumentispresent,itmustreferenceaString,whichwillreceivethedata.Theoutbufwillcontainonlythereceiveddataafterthemethodcallevenifitisnotemptyatthebeginning.

#read_nonblockjustcallstheread(2)systemcall.Itcausesallerrorstheread(2)systemcallcauses:Errno::EWOULDBLOCK,Errno::EINTR,etc.Thecallershouldcaresucherrors.

IftheexceptionisErrno::EWOULDBLOCKorErrno::AGAIN,itisextendedbyIO::WaitReadable.SoIO::WaitReadablecanbeusedtorescuetheexceptionsforretryingread_nonblock.

#read_nonblockcausesEOFErroronEOF.

Ifthereadbytebufferisnotempty,#read_nonblockreadsfromthebufferlikereadpartial.Inthiscase,theread(2)systemcallisnotcalled.

When#read_nonblockraisesanexceptionkindofIO::WaitReadable,#read_nonblockshouldnotbecalleduntilioisreadableforavoidingbusyloop.This

read_nonblock(maxlen)→stringread_nonblock(maxlen,outbuf)→outbuf

Page 381: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

canbedoneasfollows.

#emulatesblockingread(readpartial).

begin

result=io.read_nonblock(maxlen)

rescueIO::WaitReadable

IO.select([io])

retry

end

Although#read_nonblockdoesn'traiseIO::WaitWritable.OpenSSL::Buffering#read_nonblockcanraiseIO::WaitWritable.IfIOandSSLshouldbeusedpolymorphically,IO::WaitWritableshouldberescuedtoo.SeethedocumentofOpenSSL::Buffering#read_nonblockforsamplecode.

Notethatthismethodisidenticaltoreadpartialexceptthenon-blockingflagisset.

ReadsabyteaswithIO#getbyte,butraisesanEOFErroronendoffile.

Readsaone-characterstringfromios.RaisesanEOFErroronendoffile.

f=File.new("testfile")

f.readchar#=>"h"

f.readchar#=>"e"

ReadsalineaswithIO#gets,butraisesanEOFErroronendoffile.

readbyte→fixnum

readchar→string

readline(sep=$/)→stringreadline(limit)→stringreadline(sep,limit)→string

Page 382: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Readsallofthelinesinios,andreturnstheminanArray.Linesareseparatedbytheoptionalsep.Ifsepisnil,therestofthestreamisreturnedasasinglerecord.Ifthefirstargumentisaninteger,oroptionalsecondargumentisgiven,thereturningstringwouldnotbelongerthanthegivenvalueinbytes.ThestreammustbeopenedforreadingoranIOErrorwillberaised.

f=File.new("testfile")

f.readlines[0]#=>"Thisislineone\n"

ReadsatmostmaxlenbytesfromtheI/Ostream.Itblocksonlyifioshasnodataimmediatelyavailable.Itdoesn'tblockifsomedataavailable.Iftheoptionaloutbufargumentispresent,itmustreferenceaString,whichwillreceivethedata.Theoutbufwillcontainonlythereceiveddataafterthemethodcallevenifitisnotemptyatthebeginning.ItraisesEOFErroronendoffile.

readpartialisdesignedforstreamssuchaspipe,socket,tty,etc.Itblocksonlywhennodataimmediatelyavailable.Thismeansthatitblocksonlywhenfollowingallconditionshold.

thebytebufferintheIOobjectisempty.

thecontentofthestreamisempty.

thestreamisnotreachedtoEOF.

readlines(sep=$/)→arrayreadlines(limit)→arrayreadlines(sep,limit)→array

readpartial(maxlen)→stringreadpartial(maxlen,outbuf)→outbuf

Page 383: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Whenreadpartialblocks,itwaitsdataorEOFonthestream.Ifsomedataisreached,readpartialreturnswiththedata.IfEOFisreached,readpartialraisesEOFError.

Whenreadpartialdoesn'tblocks,itreturnsorraisesimmediately.Ifthebytebufferisnotempty,itreturnsthedatainthebuffer.Otherwiseifthestreamhassomecontent,itreturnsthedatainthestream.OtherwiseifthestreamisreachedtoEOF,itraisesEOFError.

r,w=IO.pipe#bufferpipecontent

w<<"abc"#"""abc".

r.readpartial(4096)#=>"abc"""""

r.readpartial(4096)#blocksbecausebufferandpipeisempty.

r,w=IO.pipe#bufferpipecontent

w<<"abc"#"""abc"

w.close#"""abc"EOF

r.readpartial(4096)#=>"abc"""EOF

r.readpartial(4096)#raisesEOFError

r,w=IO.pipe#bufferpipecontent

w<<"abc\ndef\n"#"""abc\ndef\n"

r.gets#=>"abc\n""def\n"""

w<<"ghi\n"#"def\n""ghi\n"

r.readpartial(4096)#=>"def\n""""ghi\n"

r.readpartial(4096)#=>"ghi\n"""""

Notethatreadpartialbehavessimilartosysread.Thedifferencesare:

Ifthebytebufferisnotempty,readfromthebytebufferinsteadof“sysreadforbufferedIO(IOError)”.

Itdoesn'tcauseErrno::EWOULDBLOCKandErrno::EINTR.WhenreadpartialmeetsEWOULDBLOCKandEINTRbyreadsystemcall,readpartialretrythesystemcall.

Thelatermeansthatreadpartialisnonblocking-flag

Page 384: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

insensitive.Itblocksonthesituation#sysreadcausesErrno::EWOULDBLOCKasifthefdisblockingmode.

ReassociatesioswiththeI/Ostreamgiveninother_IOortoanewstreamopenedonpath.Thismaydynamicallychangetheactualclassofthisstream.

f1=File.new("testfile")

f2=File.new("testfile")

f2.readlines[0]#=>"Thisislineone\n"

f2.reopen(f1)#=>#<File:testfile>

f2.readlines[0]#=>"Thisislineone\n"

Positionsiostothebeginningofinput,resettinglinenotozero.

f=File.new("testfile")

f.readline#=>"Thisislineone\n"

f.rewind#=>0

f.lineno#=>0

f.readline#=>"Thisislineone\n"

Notethatitcannotbeusedwithstreamssuchaspipes,ttys,andsockets.

SeekstoagivenoffsetanIntegerinthestreamaccordingtothevalueofwhence:

:CURorIO::SEEK_CUR|Seeksto_amount_pluscurrentposition

----------------------+--------------------------------------------------

:ENDorIO::SEEK_END|Seeksto_amount_plusendofstream(you

|probablywantanegativevaluefor_amount_)

----------------------+--------------------------------------------------

reopen(other_IO)→iosreopen(path,mode_str)→ios

rewind→0

seek(amount,whence=IO::SEEK_SET)→0

Page 385: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

:SETorIO::SEEK_SET|Seekstotheabsolutelocationgivenby_amount_

Example:

f=File.new("testfile")

f.seek(-13,IO::SEEK_END)#=>0

f.readline#=>"Andsoon...\n"

Ifsingleargumentisspecified,readstringfromioistaggedwiththeencodingspecified.Ifencodingisacolonseparatedtwoencodingnames“A:B”,thereadstringisconvertedfromencodingA(externalencoding)toencodingB(internalencoding),thentaggedwithB.Iftwoargumentsarespecified,thosemustbeencodingobjectsorencodingnames,andthefirstoneistheexternalencoding,andthesecondoneistheinternalencoding.Iftheexternalencodingandtheinternalencodingisspecified,optionalhashargumentspecifytheconversionoption.

ReturnsstatusinformationforiosasanobjectoftypeFile::Stat.

f=File.new("testfile")

s=f.stat

"%o"%s.mode#=>"100644"

s.blksize#=>4096

s.atime#=>WedApr0908:53:54CDT2003

set_encoding(ext_enc)→ioset_encoding("ext_enc:int_enc")→ioset_encoding(ext_enc,int_enc)→ioset_encoding("ext_enc:int_enc",opt)→ioset_encoding(ext_enc,int_enc,opt)→io

stat→stat

Page 386: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthecurrent“syncmode''ofios.Whensyncmodeistrue,alloutputisimmediatelyflushedtotheunderlyingoperatingsystemandisnotbufferedbyRubyinternally.SeealsoIO#fsync.

f=File.new("testfile")

f.sync#=>false

Setsthe“syncmode''totrueorfalse.Whensyncmodeistrue,alloutputisimmediatelyflushedtotheunderlyingoperatingsystemandisnotbufferedinternally.Returnsthenewstate.SeealsoIO#fsync.

f=File.new("testfile")

f.sync=true

(producesnooutput)

Readsmaxlenbytesfromiosusingalow-levelreadandreturnsthemasastring.Donotmixwithothermethodsthatreadfromiosoryoumaygetunpredictableresults.Iftheoptionaloutbufargumentispresent,itmustreferenceaString,whichwillreceivethedata.Theoutbufwillcontainonlythereceiveddataafterthemethodcallevenifitisnotemptyatthebeginning.RaisesSystemCallErroronerrorandEOFErroratendoffile.

f=File.new("testfile")

f.sysread(16)#=>"Thisislineone"

sync→trueorfalse

sync=boolean→boolean

sysread(maxlen[,outbuf])→string

Page 387: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Seekstoagivenoffsetinthestreamaccordingtothevalueofwhence(seeIO#seekforvaluesofwhence).Returnsthenewoffsetintothefile.

f=File.new("testfile")

f.sysseek(-13,IO::SEEK_END)#=>53

f.sysread(10)#=>"Andsoon."

Writesthegivenstringtoiosusingalow-levelwrite.Returnsthenumberofbyteswritten.Donotmixwithothermethodsthatwritetoiosoryoumaygetunpredictableresults.RaisesSystemCallErroronerror.

f=File.new("out","w")

f.syswrite("ABCDEF")#=>6

Returnsthecurrentoffset(inbytes)ofios.

f=File.new("testfile")

f.pos#=>0

f.gets#=>"Thisislineone\n"

f.pos#=>17

Aliasfor:fileno

Returnsios.

sysseek(offset,whence=IO::SEEK_SET)→integer

syswrite(string)→integer

pos→integertell→integer

to_i()

to_io→ios

Page 388: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifiosisassociatedwithaterminaldevice(tty),falseotherwise.

File.new("testfile").isatty#=>false

File.new("/dev/tty").isatty#=>true

Pushesbackbytes(passedasaparameter)ontoios,suchthatasubsequentbufferedreadwillreturnit.Onlyonebytemaybepushedbackbeforeasubsequentreadoperation(thatis,youwillbeabletoreadonlythelastofseveralbytesthathavebeenpushedback).Hasnoeffectwithunbufferedreads(suchasIO#sysread).

f=File.new("testfile")#=>#<File:testfile>

b=f.getbyte#=>0x38

f.ungetbyte(b)#=>nil

f.getbyte#=>0x38

Pushesbackonecharacter(passedasaparameter)ontoios,suchthatasubsequentbufferedcharacterreadwillreturnit.Onlyonecharactermaybepushedbackbeforeasubsequentreadoperation(thatis,youwillbeabletoreadonlythelastofseveralcharactersthathavebeenpushedback).Hasnoeffectwithunbufferedreads(suchasIO#sysread).

f=File.new("testfile")#=>#<File:testfile>

c=f.getc#=>"8"

f.ungetc(c)#=>nil

isatty→trueorfalsetty?→trueorfalse

ungetbyte(string)→nilungetbyte(integer)→nil

ungetc(string)→nil

Page 389: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

f.getc#=>"8"

Writesthegivenstringtoios.Thestreammustbeopenedforwriting.Iftheargumentisnotastring,itwillbeconvertedtoastringusingto_s.Returnsthenumberofbyteswritten.

count=$stdout.write("Thisisatest\n")

puts"Thatwas#{count}bytesofdata"

produces:

Thisisatest

Thatwas15bytesofdata

Writesthegivenstringtoiosusingthewrite(2)systemcallafterO_NONBLOCKissetfortheunderlyingfiledescriptor.

Itreturnsthenumberofbyteswritten.

#write_nonblockjustcallsthewrite(2)systemcall.Itcausesallerrorsthewrite(2)systemcallcauses:Errno::EWOULDBLOCK,Errno::EINTR,etc.Theresultmayalsobesmallerthanstring.length(partialwrite).Thecallershouldcaresucherrorsandpartialwrite.

IftheexceptionisErrno::EWOULDBLOCKorErrno::AGAIN,itisextendedbyIO::WaitWritable.SoIO::WaitWritablecanbeusedtorescuetheexceptionsforretryingwrite_nonblock.

#Createsapipe.

r,w=IO.pipe

write(string)→integer

write_nonblock(string)→integerwrite_nonblock(string[,options])→integer

Page 390: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#write_nonblockwritesonly65536bytesandreturn65536.

#(Thepipesizeis65536bytesonthisenvironment.)

s="a"*100000

pw.write_nonblock(s)#=>65536

#write_nonblockcannotwriteabyteandraiseEWOULDBLOCK(EAGAIN).

pw.write_nonblock("b")#Resourcetemporarilyunavailable(Errno::EAGAIN)

Ifthewritebufferisnotempty,itisflushedatfirst.

When#write_nonblockraisesanexceptionkindofIO::WaitWritable,#write_nonblockshouldnotbecalleduntilioiswritableforavoidingbusyloop.Thiscanbedoneasfollows.

begin

result=io.write_nonblock(string)

rescueIO::WaitWritable,Errno::EINTR

IO.select(nil,[io])

retry

end

Notethatthisdoesn'tguaranteetowritealldatainstring.Thelengthwrittenisreportedasresultanditshouldbecheckedlater.

OnsomeplatformssuchasWindows,#write_nonblockisnotsupportedaccordingtothekindoftheIOobject.Insuchcases,#write_nonblockraisesErrno::EBADF.

Byspecifying`exception:false`,theoptionshashallowsyoutoindicatethat#write_nonblockshouldnotraiseanIO::WaitWritableexception,butreturnthesymbol:wait_writableinstead.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 391: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIO::EAGAINWaitReadable

InFilesfile.c

Parentrb_eEAGAIN

IncludedModulesIO::WaitReadable

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 392: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIO::EAGAINWaitWritable

InFilesfile.c

Parentrb_eEAGAIN

IncludedModulesIO::WaitWritable

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 393: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIO::EINPROGRESSWaitReadable

InFilesfile.c

Parentrb_eEINPROGRESS

IncludedModulesIO::WaitReadable

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 394: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIO::EINPROGRESSWaitWritable

InFilesfile.c

Parentrb_eEINPROGRESS

IncludedModulesIO::WaitWritable

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 395: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIO::EWOULDBLOCKWaitReadable

InFilesfile.c

Parentrb_eEWOULDBLOCK

IncludedModulesIO::WaitReadable

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 396: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIO::EWOULDBLOCKWaitWritable

InFilesfile.c

Parentrb_eEWOULDBLOCK

IncludedModulesIO::WaitWritable

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 397: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleIO::WaitReadable

InFilesfile.c

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 398: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleIO::WaitWritable

InFilesfile.c

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 399: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIOErrorRaisedwhenanIOoperationfails.

File.open("/etc/hosts"){|f|f<<"example"}

#=>IOError:notopenedforwriting

File.open("/etc/hosts"){|f|f.close;f.read}

#=>IOError:closedstream

NotethatsomeIOfailuresraise+SystemCallError+sandthesearenotsubclassesofIOError:

File.open("does/not/exist")

#=>Errno::ENOENT:Nosuchfileordirectory-does/not/exist

InFilesio.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 400: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIndexErrorRaisedwhenthegivenindexisinvalid.

a=[:foo,:bar]

a.fetch(0)#=>:foo

a[4]#=>nil

a.fetch(4)#=>IndexError:index4outsideofarraybounds:-2...2

InFileserror.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 401: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classIntegerThisclassisthebasisforthetwoconcreteclassesthatholdwholenumbers,BignumandFixnum.

InFilesnumeric.crational.c

ParentNumeric

PublicInstanceMethods

AsintisalreadyanInteger,allthesemethodssimplyreturnthereceiver.

Synonymsareto_int,floor,ceil,truncate.

Returnsastringcontainingthecharacterrepresentedbytheint'svalueaccordingtoencoding.

65.chr#=>"A"

230.chr#=>"\346"

255.chr(Encoding::UTF_8)#=>"\303\277"

to_i→integer

chr([encoding])→string

Page 402: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returns1.

Iteratesthegivenblock,passingdecreasingvaluesfromintdowntoandincludinglimit.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

5.downto(1){|n|printn,".."}

print"Liftoff!\n"

#=>"5..4..3..2..1..Liftoff!"

Returnstrueifintisanevennumber.

AsintisalreadyanInteger,allthesemethodssimplyreturnthereceiver.

Synonymsareto_int,floor,ceil,truncate.

Returnsthegreatestcommondivisor(alwayspositive).0.gcd(x)andx.gcd(0)returnabs(x).

2.gcd(2)#=>2

3.gcd(-7)#=>1

((1<<31)-1).gcd((1<<61)-1)#=>1

Returnsanarray;[int.gcd(int2),int.lcm(int2)].

denominator→1

downto(limit){|i|block}→selfdownto(limit)→an_enumerator

even?→trueorfalse

to_i→integer

gcd(int2)→integer

gcdlcm(int2)→array

Page 403: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

2.gcdlcm(2)#=>[2,2]

3.gcdlcm(-7)#=>[1,21]

((1<<31)-1).gcdlcm((1<<61)-1)#=>[1,4951760154835678088235319297]

SinceintisalreadyanInteger,thisalwaysreturnstrue.

Returnstheleastcommonmultiple(alwayspositive).0.lcm(x)andx.lcm(0)returnzero.

2.lcm(2)#=>2

3.lcm(-7)#=>21

((1<<31)-1).lcm((1<<61)-1)#=>4951760154835678088235319297

ReturnstheIntegerequaltoint+1,sameas#next.

1.next#=>2

(-1).next#=>0

Returnsself.

Returnstrueifintisanoddnumber.

integer?→true

lcm(int2)→integer

next→integersucc→integer

numerator→self

odd?→trueorfalse

ord→self

Page 404: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheintitself.

a.ord#=>97

ThismethodisintendedforcompatibilitytocharacterconstantinRuby1.9.

Forexample,?a.ordreturns97bothin1.8and1.9.

ReturnstheIntegerequaltoint-1.

1.pred#=>0

(-1).pred#=>-2

Returnsthevalueasarational.Theoptionalargumentepsisalwaysignored.

Roundsinttoagivenprecisionindecimaldigits(default0digits).

Precisionmaybenegative.Returnsafloatingpointnumberwhenndigitsispositive,selfforzero,androunddownfornegative.

1.round#=>1

1.round(2)#=>1.0

15.round(-1)#=>20

ReturnstheIntegerequaltoint+1,sameas#next.

1.next#=>2

pred→integer

rationalize([eps])→rational

round([ndigits])→integerorfloat

next→integersucc→integer

Page 405: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(-1).next#=>0

Iteratesthegivenblockinttimes,passinginvaluesfromzerotoint-1.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

5.timesdo|i|

printi,""

end

#=>01234

AsintisalreadyanInteger,allthesemethodssimplyreturnthereceiver.

Synonymsareto_int,floor,ceil,truncate.

AsintisalreadyanInteger,allthesemethodssimplyreturnthereceiver.

Synonymsareto_int,floor,ceil,truncate.

Returnsthevalueasarational.

1.to_r#=>(1/1)

(1<<64).to_r#=>(18446744073709551616/1)

AsintisalreadyanInteger,allthesemethodssimply

times{|i|block}→selftimes→an_enumerator

to_i→integer

to_i→integer

to_r→rational

to_i→integer

Page 406: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

returnthereceiver.

Synonymsareto_int,floor,ceil,truncate.

Iteratesthegivenblock,passinginintegervaluesfromintuptoandincludinglimit.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

Forexample:

5.upto(10){|i|printi,""}

#=>5678910

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

upto(limit){|i|block}→selfupto(limit)→an_enumerator

Page 407: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classInterruptRaisedwiththeinterruptsignalisreceived,typicallybecausetheuserpressedonControl-C(onmostposixplatforms).Assuch,itisasubclassofSignalException.

begin

puts"Pressctrl-Cwhenyougetbored"

loop{}

rescueInterrupt=>e

puts"Note:YouwilltypicallyuseSignal.trapinstead."

end

produces:

Pressctrl-Cwhenyougetbored

thenwaitsuntilitisinterruptedwithControl-Candthenprints:

Note:YouwilltypicallyuseSignal.trapinstead.

InFileserror.csignal.c

Page 408: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ParentSignalException

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 409: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleKernelTheKernelmoduleisincludedbyclassObject,soitsmethodsareavailableineveryRubyobject.

TheKernelinstancemethodsaredocumentedinclassObjectwhilethemodulemethodsaredocumentedhere.Thesemethodsarecalledwithoutareceiverandthuscanbecalledinfunctionalform:

sprintf"%.1f",1.234#=>"1.2"

InFilescomplex.ccont.cerror.ceval.ceval_jump.cfile.cio.cload.cobject.cproc.cprocess.crandom.crational.cruby.csignal.cvm_backtrace.c

Page 410: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

vm_eval.cvm_trace.c

PublicInstanceMethods

ReturnsargasanArray.

Firsttriestocallto_aryonarg,thento_a.

Array(1..5)#=>[1,2,3,4,5]

Returnsx+i*y;

Complex(1,2)#=>(1+2i)

Complex('1+2i')#=>(1+2i)

Complex(nil)#=>TypeError

Complex(1,nil)#=>TypeError

Syntaxofstringform:

stringform=extraspaces,complex,extraspaces;

complex=realpart|[sign],imaginarypart

|realpart,sign,imaginarypart

|rational,"@",rational;

realpart=rational;

imaginarypart=imaginaryunit|unsignedrational,imaginaryunit;

rational=[sign],unsignedrational;

unsignedrational=numerator|numerator,"/",denominator;

numerator=integerpart|fractionalpart|integerpart,fractionalpart;

denominator=digits;

integerpart=digits;

fractionalpart=".",digits,[("e"|"E"),[sign],digits];

imaginaryunit="i"|"I"|"j"|"J";

sign="-"|"+";

digits=digit,{digit|"_",digit};

digit="0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9";

extraspaces=?\s*?;

Array(arg)→array

Complex(x[,y])→numeric

Page 411: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SeeString#to_c.

Returnsargconvertedtoafloat.Numerictypesareconverteddirectly,therestareconvertedusingarg.to_f.ConvertingnilgeneratesaTypeError.

Float(1)#=>1.0

Float("123.456")#=>123.456

ConvertsargtoaHashbycallingarg.to_hash.ReturnsanemptyHashwhenargisnilor[].

Hash([])#=>{}

Hash(nil)#=>{}

Hash(key::value)#=>{:key=>:value}

Hash([1,2,3])#=>TypeError

ConvertsargtoaFixnumorBignum.Numerictypesareconverteddirectly(withfloatingpointnumbersbeingtruncated).base(0,orbetween2and36)isabaseforintegerstringrepresentation.IfargisaString,whenbaseisomittedorequalszero,radixindicators(0,0b,and0x)arehonored.Inanycase,stringsshouldbestrictlyconformedtonumericrepresentation.ThisbehaviorisdifferentfromthatofString#to_i.Nonstringvalueswillbeconvertedbyfirsttryingto_int,thento_i.PassingnilraisesaTypeError.

Integer(123.999)#=>123

Integer("0x1a")#=>26

Integer(Time.new)#=>1204973019

Integer("0930",10)#=>930

Float(arg)→float

Hash(arg)→hash

Integer(arg,base=0)→integer

Page 412: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Integer("111",2)#=>7

Integer(nil)#=>TypeError

Returnsx/y;

Rational(1,2)#=>(1/2)

Rational('1/2')#=>(1/2)

Rational(nil)#=>TypeError

Rational(1,nil)#=>TypeError

Syntaxofstringform:

stringform=extraspaces,rational,extraspaces;

rational=[sign],unsignedrational;

unsignedrational=numerator|numerator,"/",denominator;

numerator=integerpart|fractionalpart|integerpart,fractionalpart;

denominator=digits;

integerpart=digits;

fractionalpart=".",digits,[("e"|"E"),[sign],digits];

sign="-"|"+";

digits=digit,{digit|"_",digit};

digit="0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9";

extraspaces=?\s*?;

SeeString#to_r.

ReturnsargasaString.

Firsttriestocallitsto_strmethod,thenitsto_smethod.

String(self)#=>"main"

String(self.class)#=>"Object"

String(123456)#=>"123456"

Returnsthecallednameofthecurrentmethodasa

Rational(x[,y])→numeric

String(arg)→string

__callee__→symbol

Page 413: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Symbol.Ifcalledoutsideofamethod,itreturnsnil.

Returnsthecanonicalizedabsolutepathofthedirectoryofthefilefromwhichthismethodiscalled.Itmeanssymlinksinthepathisresolved.If__FILE__isnil,itreturnsnil.ThereturnvalueequalstoFile.dirname(File.realpath(__FILE__)).

ReturnsthenameatthedefinitionofthecurrentmethodasaSymbol.Ifcalledoutsideofamethod,itreturnsnil.

Returnsthestandardoutputofrunningcmdinasubshell.Thebuilt-insyntax%x{...}usesthismethod.Sets$?totheprocessstatus.

%xdate`#=>"WedApr908:56:30CDT2003\n"

%xlstestdir`.split[1]#=>"main.rb"

%xechooops&&exit99`#=>"oops\n"

$?.exitstatus#=>99

Terminateexecutionimmediately,effectivelybycallingKernel.exit(false).Ifmsgisgiven,itiswrittentoSTDERRpriortoterminating.

__dir__→string

__method__→symbol

`cmd`→string

abortKernel::abort([msg])Process::abort([msg])

Page 414: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ConvertsblocktoaProcobject(andthereforebindsitatthepointofcall)andregistersitforexecutionwhentheprogramexits.Ifmultiplehandlersareregistered,theyareexecutedinreverseorderofregistration.

defdo_at_exit(str1)

at_exit{printstr1}

end

at_exit{puts"cruelworld"}

do_at_exit("goodbye")

exit

produces:

goodbyecruelworld

Registersfilenametobeloaded(usingKernel::require)thefirsttimethatmodule(whichmaybeaStringorasymbol)isaccessed.

autoload(:MyModule,"/usr/local/lib/modules/my_module.rb")

Returnsfilenametobeloadedifnameisregisteredasautoload.

autoload(:B,"b")

autoload?(:B)#=>"b"

ReturnsaBindingobject,describingthevariableandmethodbindingsatthepointofcall.Thisobjectcanbeusedwhencallingevaltoexecutetheevaluated

at_exit{block}→proc

autoload(module,filename)→nil

autoload?(name)→Stringornil

binding→a_binding

Page 415: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

commandinthisenvironment.SeealsothedescriptionofclassBinding.

defget_binding(param)

returnbinding

end

b=get_binding("hello")

eval("param",b)#=>"hello"

Returnstrueifyieldwouldexecuteablockinthecurrentcontext.Theiterator?formismildlydeprecated.

deftry

ifblock_given?

yield

else

"noblock"

end

end

try#=>"noblock"

try{"hello"}#=>"hello"

trydo"hello"end#=>"hello"

GeneratesaContinuationobject,whichitpassestotheassociatedblock.Youneedtorequire'continuation'beforeusingthismethod.Performingacont.callwillcausethecallcctoreturn(aswillfallingthroughtheendoftheblock).Thevaluereturnedbythecallccisthevalueoftheblock,orthevaluepassedtocont.call.SeeclassContinuationformoredetails.Alsosee#throwforanalternativemechanismforunwindingacallstack.

block_given?→trueorfalseiterator?→trueorfalse

callcc{|cont|block}→obj

Page 416: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthecurrentexecutionstack—anarraycontainingstringsintheformfile:lineorfile:line:in`method'.

Theoptionalstartparameterdeterminesthenumberofinitialstackentriestoomitfromthetopofthestack.

Asecondoptionallengthparametercanbeusedtolimithowmanyentriesarereturnedfromthestack.

Returnsnilifstartisgreaterthanthesizeofcurrentexecutionstack.

Optionallyyoucanpassarange,whichwillreturnanarraycontainingtheentrieswithinthespecifiedrange.

defa(skip)

caller(skip)

end

defb(skip)

a(skip)

end

defc(skip)

b(skip)

end

c(0)#=>["prog:2:in`a'","prog:5:in`b'","prog:8:in`c'","prog:10:in`<main>'"]

c(1)#=>["prog:5:in`b'","prog:8:in`c'","prog:11:in`<main>'"]

c(2)#=>["prog:8:in`c'","prog:12:in`<main>'"]

c(3)#=>["prog:13:in`<main>'"]

c(4)#=>[]

c(5)#=>nil

Returnsthecurrentexecutionstack—anarray

caller(start=1,length=nil)→arrayornilcaller(range)→arrayornil

caller_locations(start=1,length=nil)→arrayornilcaller_locations(range)→arrayornil

Page 417: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

containingbacktracelocationobjects.

SeeThread::Backtrace::Locationformoreinformation.

Theoptionalstartparameterdeterminesthenumberofinitialstackentriestoomitfromthetopofthestack.

Asecondoptionallengthparametercanbeusedtolimithowmanyentriesarereturnedfromthestack.

Returnsnilifstartisgreaterthanthesizeofcurrentexecutionstack.

Optionallyyoucanpassarange,whichwillreturnanarraycontainingtheentrieswithinthespecifiedrange.

catchexecutesitsblock.Ifthrowisnotcalled,theblockexecutesnormally,andcatchreturnsthevalueofthelastexpressionevaluated.

catch(1){123}#=>123

If+throw(tag2,val)+iscalled,Rubysearchesupitsstackforacatchblockwhosetaghasthesameobject_idastag2.Whenfound,theblockstopsexecutingandreturnsval(ornilifnosecondargumentwasgiventothrow).

catch(1){throw(1,456)}#=>456

catch(1){throw(1)}#=>nil

Whentagispassedasthefirstargument,catchyieldsitastheparameteroftheblock.

catch(1){|x|x+2}#=>3

catch([tag]){|tag|block}→obj

Page 418: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Whennotagisgiven,catchyieldsanewuniqueobject(asfromObject.new)astheblockparameter.Thisobjectcanthenbeusedastheargumenttothrow,andwillmatchthecorrectcatchblock.

catchdo|obj_A|

catchdo|obj_B|

throw(obj_B,123)

puts"Thisputsisnotreached"

end

puts"Thisputsisdisplayed"

456

end

#=>456

catchdo|obj_A|

catchdo|obj_B|

throw(obj_A,123)

puts"Thisputsisstillnotreached"

end

puts"Nowthisputsisalsonotreached"

456

end

#=>123

Equivalentto$_=$_.chomp(string).SeeString#chomp.Availableonlywhen-p/-ncommandlineoptionspecified.

Equivalentto($_.dup).chop!,exceptnilisneverreturned.SeeString#chop!.Availableonlywhen-p/-ncommandlineoptionspecified.

chomp→$_chomp(string)→$_

chop→$_

Page 419: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

EvaluatestheRubyexpression(s)instring.Ifbindingisgiven,whichmustbeaBindingobject,theevaluationisperformedinitscontext.Iftheoptionalfilenameandlinenoparametersarepresent,theywillbeusedwhenreportingsyntaxerrors.

defget_binding(str)

returnbinding

end

str="hello"

eval"str+'Fred'"#=>"helloFred"

eval"str+'Fred'",get_binding("bye")#=>"byeFred"

Replacesthecurrentprocessbyrunningthegivenexternalcommand,whichcantakeoneofthefollowingforms:

exec(commandline)

commandlinestringwhichispassedtothestandardshell

exec(cmdname,arg1,...)

commandnameandoneormorearguments(noshell)

exec([cmdname,argv0],arg1,...)

commandname,argvandzeroormorearguments(noshell)

Inthefirstform,thestringistakenasacommandlinethatissubjecttoshellexpansionbeforebeingexecuted.

eval(string[,binding[,filename[,lineno]]])→obj

exec([env,]command...[,options])

Page 420: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thestandardshellalwaysmeans"/bin/sh"onUnix-likesystems,sameasENV["RUBYSHELL"](orENV["COMSPEC"]onWindowsNTseries),andsimilar.

Ifthestringfromthefirstform(exec("command"))followsthesesimplerules:

nometacharacters

noshellreservedwordandnospecialbuilt-in

Rubyinvokesthecommanddirectlywithoutshell

Youcanforceshellinvocationbyadding“;”tothestring(because“;”isametacharacter).

Notethatthisbehaviorisobservablebypidobtained(returnvalueofspawn()andIO#pidforIO.popen)isthepidoftheinvokedcommand,notshell.

Inthesecondform(exec("command1","arg1",...)),thefirstistakenasacommandnameandtherestarepassedasparameterstocommandwithnoshellexpansion.

Inthethirdform(exec(["command","argv0"],"arg1",...)),startingatwo-elementarrayatthebeginningofthecommand,thefirstelementisthecommandtobeexecuted,andthesecondargumentisusedastheargv[0]value,whichmayshowupinprocesslistings.

Inordertoexecutethecommand,oneoftheexec(2)systemcallsareused,sotherunningcommandmayinheritsomeoftheenvironmentoftheoriginalprogram(includingopenfiledescriptors).

Thisbehaviorismodifiedbythegivenenvandoptionsparameters.See::spawnfordetails.

Ifthecommandfailstoexecute(typically

Page 421: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Errno::ENOENTwhenitwasnotfound)aSystemCallErrorexceptionisraised.

Thismethodmodifiesprocessattributesaccordingtogivenoptionsbeforeexec(2)systemcall.See::spawnformoredetailsaboutthegivenoptions.

Themodifiedattributesmayberetainedwhenexec(2)systemcallfails.

Forexample,hardresourcelimitsarenotrestorable.

Considertocreateachildprocessusing::spawnor#systemifthisisnotacceptable.

exec"echo*"#echoeslistoffilesincurrentdirectory

#nevergethere

exec"echo","*"#echoesanasterisk

#nevergethere

InitiatestheterminationoftheRubyscriptbyraisingtheSystemExitexception.Thisexceptionmaybecaught.Theoptionalparameterisusedtoreturnastatuscodetotheinvokingenvironment.trueandFALSEofstatusmeanssuccessandfailurerespectively.Theinterpretationofotherintegervaluesaresystemdependent.

begin

exit

puts"nevergethere"

rescueSystemExit

puts"rescuedaSystemExitexception"

end

puts"afterbeginblock"

exit(status=true)Kernel::exit(status=true)Process::exit(status=true)

Page 422: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

produces:

rescuedaSystemExitexception

afterbeginblock

Justpriortotermination,Rubyexecutesanyat_exitfunctions(seeKernel::at_exit)andrunsanyobjectfinalizers(seeObjectSpace.define_finalizer).

at_exit{puts"at_exitfunction"}

ObjectSpace.define_finalizer("string",proc{puts"infinalizer"})

exit

produces:

at_exitfunction

infinalizer

Exitstheprocessimmediately.Noexithandlersarerun.statusisreturnedtotheunderlyingsystemastheexitstatus.

Process.exit!(true)

Withnoarguments,raisestheexceptionin$!orraisesaRuntimeErrorif$!isnil.WithasingleStringargument,raisesaRuntimeErrorwiththestringasamessage.Otherwise,thefirstparametershouldbe

exit!(status=false)

raiseraise(string)raise(exception[,string[,array]])failfail(string)fail(exception[,string[,array]])

Page 423: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

thenameofanExceptionclass(oranobjectthatreturnsanExceptionobjectwhensentanexceptionmessage).Theoptionalsecondparametersetsthemessageassociatedwiththeexception,andthethirdparameterisanarrayofcallbackinformation.Exceptionsarecaughtbytherescueclauseofbegin...endblocks.

raise"Failedtocreatesocket"

raiseArgumentError,"Noparameters",caller

Createsasubprocess.Ifablockisspecified,thatblockisruninthesubprocess,andthesubprocessterminateswithastatusofzero.Otherwise,theforkcallreturnstwice,onceintheparent,returningtheprocessIDofthechild,andonceinthechild,returningnil.ThechildprocesscanexitusingKernel.exit!toavoidrunninganyat_exitfunctions.TheparentprocessshoulduseProcess.waittocollecttheterminationstatusesofitschildrenoruseProcess.detachtoregisterdisinterestintheirstatus;otherwise,theoperatingsystemmayaccumulatezombieprocesses.

Thethreadcallingforkistheonlythreadinthecreatedchildprocess.forkdoesn'tcopyotherthreads.

Ifforkisnotusable,Process.respond_to?(:fork)returnsfalse.

Notethatfork(2)isnotavailableonsomeplatformslikeWindowsandNetBSD4.Thereforeyoushouldusespawn()insteadoffork().

fork[{block}]→fixnumornilfork[{block}]→fixnumornil

Page 424: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthestringresultingfromapplyingformat_stringtoanyadditionalarguments.Withintheformatstring,anycharactersotherthanformatsequencesarecopiedtotheresult.

Thesyntaxofaformatsequenceisfollows.

%[flags][width][.precision]type

Aformatsequenceconsistsofapercentsign,followedbyoptionalflags,width,andprecisionindicators,thenterminatedwithafieldtypecharacter.Thefieldtypecontrolshowthecorrespondingsprintfargumentistobeinterpreted,whiletheflagsmodifythatinterpretation.

Thefieldtypecharactersare:

Field|IntegerFormat

------+--------------------------------------------------------------

b|Convertargumentasabinarynumber.

|Negativenumberswillbedisplayedasatwo'scomplement

|prefixedwith`..1'.

B|Equivalentto`b',butusesanuppercase0Bforprefix

|inthealternativeformatby#.

d|Convertargumentasadecimalnumber.

i|Identicalto`d'.

o|Convertargumentasanoctalnumber.

|Negativenumberswillbedisplayedasatwo'scomplement

|prefixedwith`..7'.

u|Identicalto`d'.

x|Convertargumentasahexadecimalnumber.

|Negativenumberswillbedisplayedasatwo'scomplement

|prefixedwith`..f'(representinganinfinitestringof

|leading'ff's).

X|Equivalentto`x',butusesuppercaseletters.

Field|FloatFormat

------+--------------------------------------------------------------

format(format_string[,arguments...])→stringsprintf(format_string[,arguments...])→string

Page 425: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

e|Convertfloatingpointargumentintoexponentialnotation

|withonedigitbeforethedecimalpointas[-]d.dddddde[+-]dd.

|Theprecisionspecifiesthenumberofdigitsafterthedecimal

|point(defaultingtosix).

E|Equivalentto`e',butusesanuppercaseEtoindicate

|theexponent.

f|Convertfloatingpointargumentas[-]ddd.dddddd,

|wheretheprecisionspecifiesthenumberofdigitsafter

|thedecimalpoint.

g|Convertafloatingpointnumberusingexponentialform

|iftheexponentislessthan-4orgreaterthanor

|equaltotheprecision,orindd.ddddformotherwise.

|Theprecisionspecifiesthenumberofsignificantdigits.

G|Equivalentto`g',butuseanuppercase`E'inexponentform.

a|Convertfloatingpointargumentas[-]0xh.hhhhp[+-]dd,

|whichisconsistedfromoptionalsign,"0x",fractionpart

|ashexadecimal,"p",andexponentialpartasdecimal.

A|Equivalentto`a',butuseuppercase`X'and`P'.

Field|OtherFormat

------+--------------------------------------------------------------

c|Argumentisthenumericcodeforasinglecharacteror

|asinglecharacterstringitself.

p|Thevaluingofargument.inspect.

s|Argumentisastringtobesubstituted.Iftheformat

|sequencecontainsaprecision,atmostthatmanycharacters

|willbecopied.

%|Apercentsignitselfwillbedisplayed.Noargumenttaken.

Theflagsmodifiesthebehavioroftheformats.Theflagcharactersare:

Flag|Appliesto|Meaning

---------+---------------+-----------------------------------------

space|bBdiouxX|Leaveaspaceatthestartof

|aAeEfgG|non-negativenumbers.

|(numericfmt)|For`o',`x',`X',`b'and`B',use

||aminussignwithabsolutevaluefor

||negativevalues.

---------+---------------+-----------------------------------------

(digit)$|all|Specifiestheabsoluteargumentnumber

||forthisfield.Absoluteandrelative

||argumentnumberscannotbemixedina

||sprintfstring.

---------+---------------+-----------------------------------------

#|bBoxX|Useanalternativeformat.

Page 426: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

|aAeEfgG|Fortheconversions`o',increasetheprecision

||untilthefirstdigitwillbe`0'if

||itisnotformattedascomplements.

||Fortheconversions`x',`X',`b'and`B'

||onnon-zero,prefixtheresultwith``0x'',

||``0X'',``0b''and``0B'',respectively.

||For`a',`A',`e',`E',`f',`g',and'G',

||forceadecimalpointtobeadded,

||evenifnodigitsfollow.

||For`g'and'G',donotremovetrailingzeros.

---------+---------------+-----------------------------------------

+|bBdiouxX|Addaleadingplussigntonon-negative

|aAeEfgG|numbers.

|(numericfmt)|For`o',`x',`X',`b'and`B',use

||aminussignwithabsolutevaluefor

||negativevalues.

---------+---------------+-----------------------------------------

-|all|Left-justifytheresultofthisconversion.

---------+---------------+-----------------------------------------

0(zero)|bBdiouxX|Padwithzeros,notspaces.

|aAeEfgG|For`o',`x',`X',`b'and`B',radix-1

|(numericfmt)|isusedfornegativenumbersformattedas

||complements.

---------+---------------+-----------------------------------------

*|all|Usethenextargumentasthefieldwidth.

||Ifnegative,left-justifytheresult.Ifthe

||asteriskisfollowedbyanumberandadollar

||sign,usetheindicatedargumentasthewidth.

Examplesofflags:

#`+'andspaceflagspecifiesthesignofnon-negativenumbers.

sprintf("%d",123)#=>"123"

sprintf("%+d",123)#=>"+123"

sprintf("%d",123)#=>"123"

#`#'flagfor`o'increasesnumberofdigitstoshow`0'.

#`+'andspaceflagchangesformatofnegativenumbers.

sprintf("%o",123)#=>"173"

sprintf("%#o",123)#=>"0173"

sprintf("%+o",-123)#=>"-173"

sprintf("%o",-123)#=>"..7605"

sprintf("%#o",-123)#=>"..7605"

#`#'flagfor`x'addaprefix`0x'fornon-zeronumbers.

#`+'andspaceflagdisablescomplementsfornegativenumbers.

Page 427: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

sprintf("%x",123)#=>"7b"

sprintf("%#x",123)#=>"0x7b"

sprintf("%+x",-123)#=>"-7b"

sprintf("%x",-123)#=>"..f85"

sprintf("%#x",-123)#=>"0x..f85"

sprintf("%#x",0)#=>"0"

#`#'for`X'usestheprefix`0X'.

sprintf("%X",123)#=>"7B"

sprintf("%#X",123)#=>"0X7B"

#`#'flagfor`b'addaprefix`0b'fornon-zeronumbers.

#`+'andspaceflagdisablescomplementsfornegativenumbers.

sprintf("%b",123)#=>"1111011"

sprintf("%#b",123)#=>"0b1111011"

sprintf("%+b",-123)#=>"-1111011"

sprintf("%b",-123)#=>"..10000101"

sprintf("%#b",-123)#=>"0b..10000101"

sprintf("%#b",0)#=>"0"

#`#'for`B'usestheprefix`0B'.

sprintf("%B",123)#=>"1111011"

sprintf("%#B",123)#=>"0B1111011"

#`#'for`e'forcestoshowthedecimalpoint.

sprintf("%.0e",1)#=>"1e+00"

sprintf("%#.0e",1)#=>"1.e+00"

#`#'for`f'forcestoshowthedecimalpoint.

sprintf("%.0f",1234)#=>"1234"

sprintf("%#.0f",1234)#=>"1234."

#`#'for`g'forcestoshowthedecimalpoint.

#Italsodisablesstrippinglowestzeros.

sprintf("%g",123.4)#=>"123.4"

sprintf("%#g",123.4)#=>"123.400"

sprintf("%g",123456)#=>"123456"

sprintf("%#g",123456)#=>"123456."

Thefieldwidthisanoptionalinteger,followedoptionallybyaperiodandaprecision.Thewidthspecifiestheminimumnumberofcharactersthatwillbewrittentotheresultforthisfield.

Examplesofwidth:

Page 428: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#paddingisdonebyspaces,width=20

#0orradix-1.<------------------>

sprintf("%20d",123)#=>"123"

sprintf("%+20d",123)#=>"+123"

sprintf("%020d",123)#=>"00000000000000000123"

sprintf("%+020d",123)#=>"+0000000000000000123"

sprintf("%020d",123)#=>"0000000000000000123"

sprintf("%-20d",123)#=>"123"

sprintf("%-+20d",123)#=>"+123"

sprintf("%-20d",123)#=>"123"

sprintf("%020x",-123)#=>"..ffffffffffffffff85"

Fornumericfields,theprecisioncontrolsthenumberofdecimalplacesdisplayed.Forstringfields,theprecisiondeterminesthemaximumnumberofcharacterstobecopiedfromthestring.(Thus,theformatsequence%10.10swillalwayscontributeexactlytencharacterstotheresult.)

Examplesofprecisions:

#precisionfor`d','o','x'and'b'is

#minimumnumberofdigits<------>

sprintf("%20.8d",123)#=>"00000123"

sprintf("%20.8o",123)#=>"00000173"

sprintf("%20.8x",123)#=>"0000007b"

sprintf("%20.8b",123)#=>"01111011"

sprintf("%20.8d",-123)#=>"-00000123"

sprintf("%20.8o",-123)#=>"..777605"

sprintf("%20.8x",-123)#=>"..ffff85"

sprintf("%20.8b",-11)#=>"..110101"

#"0x"and"0b"for`#x'and`#b'isnotcountedfor

#precisionbut"0"for`#o'iscounted.<------>

sprintf("%#20.8d",123)#=>"00000123"

sprintf("%#20.8o",123)#=>"00000173"

sprintf("%#20.8x",123)#=>"0x0000007b"

sprintf("%#20.8b",123)#=>"0b01111011"

sprintf("%#20.8d",-123)#=>"-00000123"

sprintf("%#20.8o",-123)#=>"..777605"

sprintf("%#20.8x",-123)#=>"0x..ffff85"

sprintf("%#20.8b",-11)#=>"0b..110101"

#precisionfor`e'isnumberof

Page 429: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#digitsafterthedecimalpoint<------>

sprintf("%20.8e",1234.56789)#=>"1.23456789e+03"

#precisionfor`f'isnumberof

#digitsafterthedecimalpoint<------>

sprintf("%20.8f",1234.56789)#=>"1234.56789000"

#precisionfor`g'isnumberof

#significantdigits<------->

sprintf("%20.8g",1234.56789)#=>"1234.5679"

#<------->

sprintf("%20.8g",123456789)#=>"1.2345679e+08"

#precisionfor`s'is

#maximumnumberofcharacters<------>

sprintf("%20.8s","stringtest")#=>"stringt"

Examples:

sprintf("%d%04x",123,123)#=>"123007b"

sprintf("%08b'%4s'",123,123)#=>"01111011'123'"

sprintf("%1$*2$s%2$d%1$s","hello",8)#=>"hello8hello"

sprintf("%1$*2$s%2$d","hello",-8)#=>"hello-8"

sprintf("%+g:%g:%-g",1.23,1.23,1.23)#=>"+1.23:1.23:1.23"

sprintf("%u",-123)#=>"-123"

Formorecomplexformatting,Rubysupportsareferencebyname.%<name>sstyleusesformatstyle,but%{name}styledoesn't.

Examples:

sprintf("%<foo>d:%<bar>f",{:foo=>1,:bar=>2})

#=>1:2.000000

sprintf("%{foo}f",{:foo=>1})

#=>"1f"

gets(sep=$/)→stringornilgets(limit)→stringornilgets(sep,limit)→stringornil

Page 430: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returns(andassignsto$_)thenextlinefromthelistoffilesinARGV(or$*),orfromstandardinputifnofilesarepresentonthecommandline.Returnsnilatendoffile.Theoptionalargumentspecifiestherecordseparator.Theseparatorisincludedwiththecontentsofeachrecord.Aseparatorofnilreadstheentirecontents,andazero-lengthseparatorreadstheinputoneparagraphatatime,whereparagraphsaredividedbytwoconsecutivenewlines.Ifthefirstargumentisaninteger,oroptionalsecondargumentisgiven,thereturningstringwouldnotbelongerthanthegivenvalueinbytes.IfmultiplefilenamesarepresentinARGV,+gets(nil)+willreadthecontentsonefileatatime.

ARGV<<"testfile"

printwhilegets

produces:

Thisislineone

Thisislinetwo

Thisislinethree

Andsoon...

Thestyleofprogrammingusing$_asanimplicitparameterisgraduallylosingfavorintheRubycommunity.

Returnsanarrayofthenamesofglobalvariables.

global_variables.grep/std/#=>[:$stdin,:$stdout,:$stderr]

global_variables→array

gsub(pattern,replacement)→$_gsub(pattern){|...|block}→$_

Page 431: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Equivalentto$_.gsub...,exceptthat$_willbeupdatedifsubstitutionoccurs.Availableonlywhen-p/-ncommandlineoptionspecified.

Returnstrueifyieldwouldexecuteablockinthecurrentcontext.Theiterator?formismildlydeprecated.

deftry

ifblock_given?

yield

else

"noblock"

end

end

try#=>"noblock"

try{"hello"}#=>"hello"

trydo"hello"end#=>"hello"

EquivalenttoProc.new,excepttheresultingProcobjectscheckthenumberofparameterspassedwhencalled.

LoadsandexecutestheRubyprograminthefilefilename.Ifthefilenamedoesnotresolvetoanabsolutepath,thefileissearchedforinthelibrarydirectorieslistedin$:.Iftheoptionalwrapparameteristrue,theloadedscriptwillbeexecutedunderananonymousmodule,protectingthecallingprogram'sglobalnamespace.Innocircumstancewillanylocalvariablesintheloadedfilebepropagatedtothe

block_given?→trueorfalseiterator?→trueorfalse

lambda{|...|block}→a_proc

load(filename,wrap=false)→true

Page 432: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

loadingenvironment.

Returnsthenamesofthecurrentlocalvariables.

fred=1

foriin1..10

#...

end

local_variables#=>[:fred,:i]

Repeatedlyexecutestheblock.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

loopdo

print"Input:"

line=gets

breakif!lineorline=~/^qQ/

#...

end

StopIterationraisedintheblockbreakstheloop.

CreatesanIOobjectconnectedtothegivenstream,file,orsubprocess.

Ifpathdoesnotstartwithapipecharacter(|),treatitasthenameofafiletoopenusingthespecifiedmode(defaultingto“r”).

local_variables→array

loop{block}loop→an_enumerator

open(path[,mode[,perm]][,opt])→ioornilopen(path[,mode[,perm]][,opt]){|io|block}→obj

Page 433: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Themodeiseitherastringoraninteger.Ifitisaninteger,itmustbebitwise-orofopen(2)flags,suchasFile::RDWRorFile::EXCL.Ifitisastring,itiseither“fmode”,“fmode:ext_enc”,or“fmode:ext_enc:int_enc”.

SeethedocumentationofIO.newforfulldocumentationofthemodestringdirectives.

Ifafileisbeingcreated,itsinitialpermissionsmaybesetusingthepermparameter.SeeFile.newandtheopen(2)andchmod(2)manpagesforadescriptionofpermissions.

Ifablockisspecified,itwillbeinvokedwiththeIOobjectasaparameter,andtheIOwillbeautomaticallyclosedwhentheblockterminates.Thecallreturnsthevalueoftheblock.

Ifpathstartswithapipecharacter("|"),asubprocessiscreated,connectedtothecallerbyapairofpipes.ThereturnedIOobjectmaybeusedtowritetothestandardinputandreadfromthestandardoutputofthissubprocess.

Ifthecommandfollowingthepipeisasingleminussign("|-"),Rubyforks,andthissubprocessisconnectedtotheparent.Ifthecommandisnot"-",thesubprocessrunsthecommand.

Whenthesubprocessisruby(openedvia"|-"),theopencallreturnsnil.Ifablockisassociatedwiththeopencall,thatblockwillruntwice—onceintheparentandonceinthechild.

TheblockparameterwillbeanIOobjectintheparentandnilinthechild.Theparent'sIOobjectwillbeconnectedtothechild's$stdinand$stdout.Thesubprocesswillbeterminatedattheendoftheblock.

Page 434: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ExamplesReadingfrom“testfile”:

open("testfile")do|f|

printf.gets

end

Produces:

Thisislineone

Openasubprocessandreaditsoutput:

cmd=open("|date")

printcmd.gets

cmd.close

Produces:

WedApr908:56:31CDT2003

OpenasubprocessrunningthesameRubyprogram:

f=open("|-","w+")

iff==nil

puts"inChild"

exit

else

puts"Got:#{f.gets}"

end

Produces:

Got:inChild

OpenasubprocessusingablocktoreceivetheIOobject:

open"|-"do|f|

iffthen

#parentprocess

puts"Got:#{f.gets}"

else

#childprocess

puts"inChild"

Page 435: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

end

Produces:

Got:inChild

Foreachobject,directlywritesobj.inspectfollowedbyanewlinetotheprogram'sstandardoutput.

S=Struct.new(:name,:state)

s=S['dave','TX']

ps

produces:

#<Sname="dave",state="TX">

Printseachobjectinturnto$stdout.Iftheoutputfieldseparator($,)isnotnil,itscontentswillappearbetweeneachfield.Iftheoutputrecordseparator($\</code>)isnotnil,itwillbeappendedtothe

output.Ifnoargumentsaregiven,prints

<code>$_.Objectsthataren'tstringswillbeconvertedbycallingtheirto_smethod.

print"cat",[1,2,3],99,"\n"

$,=","

$\="\n"

print"cat",[1,2,3],99

produces:

cat12399

p(obj)→objp(obj1,obj2,...)→[obj,...]p()→nil

print(obj,...)→nil

Page 436: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

cat,1,2,3,99

Equivalentto:

io.write(sprintf(string,obj,...))

or

$stdout.write(sprintf(string,obj,...))

EquivalenttoProc.new.

Equivalentto:

$stdout.putc(int)

RefertothedocumentationforIO#putcforimportantinformationregardingmulti-bytecharacters.

Equivalentto

$stdout.puts(obj,...)

printf(io,string[,obj...])→nilprintf(string[,obj...])→nil

proc{|...|block}→a_proc

putc(int)→int

puts(obj,...)→nil

raiseraise(string)raise(exception[,string[,array]])failfail(string)

Page 437: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Withnoarguments,raisestheexceptionin$!orraisesaRuntimeErrorif$!isnil.WithasingleStringargument,raisesaRuntimeErrorwiththestringasamessage.Otherwise,thefirstparametershouldbethenameofanExceptionclass(oranobjectthatreturnsanExceptionobjectwhensentanexceptionmessage).Theoptionalsecondparametersetsthemessageassociatedwiththeexception,andthethirdparameterisanarrayofcallbackinformation.Exceptionsarecaughtbytherescueclauseofbegin...endblocks.

raise"Failedtocreatesocket"

raiseArgumentError,"Noparameters",caller

Ifcalledwithoutanargument,orifmax.to_i.abs==0,randreturnsapseudo-randomfloatingpointnumberbetween0.0and1.0,including0.0andexcluding1.0.

rand#=>0.2725926052826416

Whenmax.absisgreaterthanorequalto1,randreturnsapseudo-randomintegergreaterthanorequalto0andlessthanmax.to_i.abs.

rand(100)#=>12

WhenmaxisaRange,randreturnsarandomnumberwhererange.member?(number)==true.

Negativeorfloatingpointvaluesformaxareallowed,butmaygivesurprisingresults.

rand(-100)#=>87

rand(-0.5)#=>0.8130921818028143

rand(1.9)#equivalenttorand(1),whichisalways0

fail(exception[,string[,array]])

rand(max=0)→number

Page 438: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#srandmaybeusedtoensurethatsequencesofrandomnumbersarereproduciblebetweendifferentrunsofaprogram.

SeealsoRandom#rand.

EquivalenttoKernel::gets,exceptreadlineraisesEOFErroratendoffile.

ReturnsanarraycontainingthelinesreturnedbycallingKernel.gets(sep)untiltheendoffile.

Loadsthegivenname,returningtrueifsuccessfulandfalseifthefeatureisalreadyloaded.

Ifthefilenamedoesnotresolvetoanabsolutepath,itwillbesearchedforinthedirectorieslistedin$LOAD_PATH($:).

Ifthefilenamehastheextension“.rb”,itisloadedasasourcefile;iftheextensionis“.so”,“.o”,or“.dll”,orthedefaultsharedlibraryextensiononthecurrentplatform,RubyloadsthesharedlibraryasaRubyextension.Otherwise,Rubytriesadding“.rb”,“.so”,andsoontothenameuntilfound.Ifthefilenamedcannotbefound,aLoadErrorwillberaised.

readline(sep=$/)→stringreadline(limit)→stringreadline(sep,limit)→string

readlines(sep=$/)→arrayreadlines(limit)→arrayreadlines(sep,limit)→array

require(name)→trueorfalse

Page 439: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ForRubyextensionsthefilenamegivenmayuseanysharedlibraryextension.Forexample,onLinuxthesocketextensionis“socket.so”andrequire'socket.dll'willloadthesocketextension.

Theabsolutepathoftheloadedfileisaddedto$LOADED_FEATURES($").Afilewillnotbeloadedagainifitspathalreadyappearsin$".Forexample,require'a';require'./a'willnotloada.rbagain.

require"my-library.rb"

require"db-driver"

Anyconstantsorglobalswithintheloadedsourcefilewillbeavailableinthecallingprogram'sglobalnamespace.However,localvariableswillnotbepropagatedtotheloadingenvironment.

Rubytriestoloadthelibrarynamedstringrelativetotherequiringfile'spath.Ifthefile'spathcannotbedeterminedaLoadErrorisraised.Ifafileisloadedtrueisreturnedandfalseotherwise.

Callsselect(2)systemcall.ItmonitorsgivenarraysofIOobjects,waitsoneormoreofIOobjectsreadyforreading,arereadyforwriting,andhavependingexceptionsrespectively,andreturnsanarraythatcontainsarraysofthoseIOobjects.ItwillreturnnilifoptionaltimeoutvalueisgivenandnoIOobjectisreadyintimeoutseconds.

require_relative(string)→trueorfalse

select(read_array[,write_array[,error_array[,timeout]]])→arrayornil

Page 440: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

IO.selectpeeksthebufferofIOobjectsfortestingreadability.IftheIObufferisnotempty,IO.selectimmediatelynotifyreadability.This“peek”isonlyhappenforIOobjects.ItisnothappenforIO-likeobjectssuchasOpenSSL::SSL::SSLSocket.

ThebestwaytouseIO.selectisinvokingitafternonblockingmethodssuchasread_nonblock,write_nonblock,etc.ThemethodsraisesanexceptionwhichisextendedbyIO::WaitReadableorIO::WaitWritable.ThemodulesnotifyhowthecallershouldwaitwithIO.select.IfIO::WaitReadableisraised,thecallershouldwaitforreading.IfIO::WaitWritableisraised,thecallershouldwaitforwriting.

So,blockingread(readpartial)canbeemulatedusingread_nonblockandIO.selectasfollows:

begin

result=io_like.read_nonblock(maxlen)

rescueIO::WaitReadable

IO.select([io_like])

retry

rescueIO::WaitWritable

IO.select(nil,[io_like])

retry

end

Especially,thecombinationofnonblockingmethodsandIO.selectispreferredforIOlikeobjectssuchasOpenSSL::SSL::SSLSocket.Ithasto_iomethodtoreturnunderlyingIOobject.IO.selectcallsto_iotoobtainthefiledescriptortowait.

ThismeansthatreadabilitynotifiedbyIO.selectdoesn'tmeanreadabilityfromOpenSSL::SSL::SSLSocketobject.

Page 441: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

MostpossiblesituationisOpenSSL::SSL::SSLSocketbufferssomedata.IO.selectdoesn'tseethebuffer.SoIO.selectcanblockwhenOpenSSL::SSL::SSLSocket#readpartialdoesn'tblock.

Howeverseveralmorecomplicatedsituationexists.

SSLisaprotocolwhichissequenceofrecords.Therecordconsistsmultiplebytes.So,theremotesideofSSLsendsapartialrecord,IO.selectnotifiesreadabilitybutOpenSSL::SSL::SSLSocketcannotdecryptabyteandOpenSSL::SSL::SSLSocket#readpartialwillblocks.

Also,theremotesidecanrequestSSLrenegotiationwhichforcesthelocalSSLenginewritessomedata.ThismeansOpenSSL::SSL::SSLSocket#readpartialmayinvokewritesystemcallanditcanblock.Insuchsituation,OpenSSL::SSL::SSLSocket#read_nonblockraisesIO::WaitWritableinsteadofblocking.So,thecallershouldwaitforreadyforwritabilityasaboveexample.

ThecombinationofnonblockingmethodsandIO.selectisalsousefulforstreamssuchastty,pipesocketsocketwhenmultipleprocessreadformastream.

Finally,Linuxkerneldevelopersdoesn'tguaranteethatreadabilityofselect(2)meansreadabilityoffollowingread(2)evenforsingleprocess.Seeselect(2)manualonGNU/Linuxsystem.

InvokingIO.selectbeforeIO#readpartialworkswellinusual.HoweveritisnotthebestwaytouseIO.select.

Thewritabilitynotifiedbyselect(2)doesn'tshowhowmanybyteswritable.IO#writemethodblocksuntil

Page 442: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

givenwholestringiswritten.So,IO#write(twoormorebytes)canblockafterwritabilityisnotifiedbyIO.select.IO#write_nonblockisrequiredtoavoidtheblocking.

Blockingwrite(write)canbeemulatedusingwrite_nonblockandIO.selectasfollows:IO::WaitReadableshouldalsoberescuedforSSLrenegotiationinOpenSSL::SSL::SSLSocket.

while0<string.bytesize

begin

written=io_like.write_nonblock(string)

rescueIO::WaitReadable

IO.select([io_like])

retry

rescueIO::WaitWritable

IO.select(nil,[io_like])

retry

end

string=string.byteslice(written..-1)

end

Parametersread_arrayanarrayofIOobjectsthatwaituntilreadyforread

write_arrayanarrayofIOobjectsthatwaituntilreadyforwrite

error_arrayanarrayofIOobjectsthatwaitforexceptions

timeoutanumericvalueinsecond

Examplerp,wp=IO.pipe

Page 443: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

mesg="ping"

100.times{

#IO.selectfollowsIO#read.NotthebestwaytouseIO.select.

rs,ws,=IO.select([rp],[wp])

ifr=rs[0]

ret=r.read(5)

printret

caseret

when/ping/

mesg="pong\n"

when/pong/

mesg="ping"

end

end

ifw=ws[0]

w.write(mesg)

end

}

produces:

pingpong

pingpong

pingpong

(snipped)

ping

Establishesprocasthehandlerfortracing,ordisablestracingiftheparameterisnil.

Note:thismethodisobsolete,pleaseuseTracePointinstead.

proctakesuptosixparameters:

aneventname

afilename

alinenumber

anobjectid

set_trace_func(proc)→procset_trace_func(nil)→nil

Page 444: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

abinding

thenameofaclass

procisinvokedwheneveraneventoccurs.

Eventsare:c-call

callaC-languageroutine

c-return

returnfromaC-languageroutine

call

callaRubymethod

class

startaclassormoduledefinition),

end

finishaclassormoduledefinition),

line

executecodeonanewline

raise

raiseanexception

return

returnfromaRubymethod

Tracingisdisabledwithinthecontextofproc.

classTest

deftest

a=1

b=2

end

end

set_trace_funcproc{|event,file,line,id,binding

printf"%8s%s:%-2d%10s%8s\n",event,file,line

}

t=Test.new

t.test

lineprog.rb:11false

Page 445: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

c-callprog.rb:11newClass

c-callprog.rb:11initializeObject

c-returnprog.rb:11initializeObject

c-returnprog.rb:11newClass

lineprog.rb:12false

callprog.rb:2testTest

lineprog.rb:3testTest

lineprog.rb:4testTest

returnprog.rb:4testTest

Suspendsthecurrentthreadfordurationseconds(whichmaybeanynumber,includingaFloatwithfractionalseconds).Returnstheactualnumberofsecondsslept(rounded),whichmaybelessthanthataskedforifanotherthreadcallsThread#run.Calledwithoutanargument,sleep()willsleepforever.

Time.new#=>2008-03-0819:56:19+0900

sleep1.2#=>1

Time.new#=>2008-03-0819:56:20+0900

sleep1.9#=>2

Time.new#=>2008-03-0819:56:22+0900

spawnexecutesspecifiedcommandandreturnitspid.

pid=spawn("tarxfruby-2.0.0-p195.tar.bz2")

Process.waitpid

pid=spawn(RbConfig.ruby,"-eputs'Hello,world!'")

Process.waitpid

Thismethodissimilarto#systembutitdoesn'twaitforthecommandtofinish.

sleep([duration])→fixnum

spawn([env,]command...[,options])→pidspawn([env,]command...[,options])→pid

Page 446: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

TheparentprocessshoulduseProcess.waittocollecttheterminationstatusofitschildoruseProcess.detachtoregisterdisinterestintheirstatus;otherwise,theoperatingsystemmayaccumulatezombieprocesses.

spawnhasbunchofoptionstospecifyprocessattributes:

env:hash

name=>val:settheenvironmentvariable

name=>nil:unsettheenvironmentvariable

command...:

commandline:commandlinestringwhich

cmdname,arg1,...:commandnameandoneor

[cmdname,argv0],arg1,...:commandname,argv[0]

options:hash

clearingenvironmentvariables:

:unsetenv_others=>true:clearenvironmentvariables

:unsetenv_others=>false:don'tclear(default)

processgroup:

:pgroup=>trueor0:makeanewprocessgroup

:pgroup=>pgid:jointospecifiedprocessgroup

:pgroup=>nil:don'tchangetheprocessgroup

createnewprocessgroup:Windowsonly

:new_pgroup=>true:thenewprocessistheroot

:new_pgroup=>false:don'tcreateanewprocessgroup(default)

resourcelimit:resourcenameiscore,cpu,data,etc.SeeProcess.setrlimit.

:rlimit_resourcename=>limit

:rlimit_resourcename=>[cur_limit,max_limit]

umask:

:umask=>int

redirection:

key:

FD:singlefiledescriptorinchildprocess

[FD,FD,...]:multiplefiledescriptorinchildprocess

value:

FD:redirecttothefiledescriptorinparentprocess

string:redirecttofilewithopen(string,"r"or"w")

[string]:redirecttofilewithopen(string,File::RDONLY)

[string,open_mode]:redirecttofilewithopen(string,open_mode,0644)

[string,open_mode,perm]:redirecttofilewithopen(string,open_mode,perm)

[:child,FD]:redirecttotheredirectedfiledescriptor

:close:closethefiledescriptorinchildprocess

FDisoneoffollows

Page 447: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

:in:thefiledescriptor0whichisthestandardinput

:out:thefiledescriptor1whichisthestandardoutput

:err:thefiledescriptor2whichisthestandarderror

integer:thefiledescriptorofspecifiedtheinteger

io:thefiledescriptorspecifiedasio.fileno

filedescriptorinheritance:closenon-redirectednon-standardfds(3,4,5,...)ornot

:close_others=>true:don'tinherit

currentdirectory:

:chdir=>str

The'cmdname,arg1,...'formdoesnotusetheshell

ondifferentOSes,differentthingsareprovidedas

commands.Anexampleofthisis'echo',whichisabuilt

onWindows,butisanormalprogramonLinuxandMac

Thismeansthat%xProcess.spawn'echo','%Path%'`will

thecontentsofthe%x%Path%`environmentvariableon

but%xProcess.spawn'echo','$PATH'`printstheliteral

Ifahashisgivenasenv,theenvironmentisupdatedbyenvbeforeexec(2)inthechildprocess.Ifapairinenvhasnilasthevalue,thevariableisdeleted.

#setFOOasBARandunsetBAZ.

pid=spawn({"FOO"=>"BAR","BAZ"=>nil},command)

Ifahashisgivenasoptions,itspecifiesprocessgroup,createnewprocessgroup,resourcelimit,currentdirectory,umaskandredirectsforthechildprocess.Also,itcanbespecifiedtoclearenvironmentvariables.

The:unsetenv_otherskeyinoptionsspecifiestoclearenvironmentvariables,otherthanspecifiedbyenv.

pid=spawn(command,:unsetenv_others=>true)#noenvironmentvariable

pid=spawn({"FOO"=>"BAR"},command,:unsetenv_others=

The:pgroupkeyinoptionsspecifiesaprocessgroup.Thecorrespondingvalueshouldbetrue,zero

Page 448: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

orpositiveinteger.trueandzeromeanstheprocessshouldbeaprocessleaderofanewprocessgroup.Othervaluesspecifiesaprocessgrouptobebelongs.

pid=spawn(command,:pgroup=>true)#processleader

pid=spawn(command,:pgroup=>10)#belongstotheprocessgroup10

The:new_pgroupkeyinoptionsspecifiestopassCREATE_NEW_PROCESS_GROUPflagtoCreateProcessW()thatisWindowsAPI.ThisoptionisonlyforWindows.truemeansthenewprocessistherootprocessofthenewprocessgroup.ThenewprocesshasCTRL+Cdisabled.ThisflagisnecessaryforProcess.kill(:SIGINT,pid)onthesubprocess.:new_pgroupisfalsebydefault.

pid=spawn(command,:new_pgroup=>true)#newprocessgroup

pid=spawn(command,:new_pgroup=>false)#sameprocessgroup

The:rlimit_fookeyspecifiesaresourcelimit.fooshouldbeoneofresourcetypessuchascore.Thecorrespondingvalueshouldbeanintegeroranarraywhichhaveoneortwointegers:sameascur_limitandmax_limitargumentsforProcess.setrlimit.

cur,max=Process.getrlimit(:CORE)

pid=spawn(command,:rlimit_core=>[0,max])#disablecoretemporary.

pid=spawn(command,:rlimit_core=>max)#enablecoredump

pid=spawn(command,:rlimit_core=>0)#neverdumpcore.

The:umaskkeyinoptionsspecifiestheumask.

pid=spawn(command,:umask=>077)

The:in,:out,:err,afixnum,anIOandanarraykeyspecifiesaredirection.Theredirectionmapsafiledescriptorinthechildprocess.

Page 449: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Forexample,stderrcanbemergedintostdoutasfollows:

pid=spawn(command,:err=>:out)

pid=spawn(command,2=>1)

pid=spawn(command,STDERR=>:out)

pid=spawn(command,STDERR=>STDOUT)

Thehashkeysspecifiesafiledescriptorinthechildprocessstartedbyspawn.:err,2andSTDERRspecifiesthestandarderrorstream(stderr).

Thehashvaluesspecifiesafiledescriptorintheparentprocesswhichinvokesspawn.:out,1andSTDOUTspecifiesthestandardoutputstream(stdout).

Intheaboveexample,thestandardoutputinthechildprocessisnotspecified.Soitisinheritedfromtheparentprocess.

Thestandardinputstream(stdin)canbespecifiedby:in,0andSTDIN.

Afilenamecanbespecifiedasahashvalue.

pid=spawn(command,:in=>"/dev/null")#readmode

pid=spawn(command,:out=>"/dev/null")#writemode

pid=spawn(command,:err=>"log")#writemode

pid=spawn(command,[:out,:err]=>"/dev/null")#writemode

pid=spawn(command,3=>"/dev/null")#readmode

Forstdoutandstderr(andcombinationofthem),itisopenedinwritemode.Otherwisereadmodeisused.

Forspecifyingflagsandpermissionoffilecreationexplicitly,anarrayisusedinstead.

pid=spawn(command,:in=>["file"])#readmodeisassumed

pid=spawn(command,:in=>["file","r"])

pid=spawn(command,:out=>["log","w"])#0644assumed

pid=spawn(command,:out=>["log","w",0600])

pid=spawn(command,:out=>["log",File::WRONLY|File::

Page 450: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thearrayspecifiesafilename,flagsandpermission.Theflagscanbeastringoraninteger.Iftheflagsisomittedornil,File::RDONLYisassumed.Thepermissionshouldbeaninteger.Ifthepermissionisomittedornil,0644isassumed.

IfanarrayofIOsandintegersarespecifiedasahashkey,alltheelementsareredirected.

#stdoutandstderrisredirectedtologfile.

#Thefile"log"isopenedjustonce.

pid=spawn(command,[:out,:err]=>["log","w"])

Anotherwaytomergemultiplefiledescriptorsis[:child,fd].[:child,fd]meansthefiledescriptorinthechildprocess.Thisisdifferentfromfd.Forexample,:err=>:outmeansredirectingchildstderrtoparentstdout.But:err=>[:child,:out]meansredirectingchildstderrtochildstdout.Theydifferifstdoutisredirectedinthechildprocessasfollows.

#stdoutandstderrisredirectedtologfile.

#Thefile"log"isopenedjustonce.

pid=spawn(command,:out=>["log","w"],:err=>[:child

[:child,:out]canbeusedtomergestderrintostdoutinIO.popen.Inthiscase,IO.popenredirectsstdouttoapipeinthechildprocessand[:child,:out]referstheredirectedstdout.

io=IO.popen(["sh","-c","echoout;echoerr>&2",:

pio.read#=>"out\nerr\n"

The:chdirkeyinoptionsspecifiesthecurrentdirectory.

pid=spawn(command,:chdir=>"/var/tmp")

spawnclosesallnon-standardunspecified

Page 451: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

descriptorsbydefault.The“standard”descriptorsare0,1and2.Thisbehaviorisspecifiedby:close_othersoption.:close_othersdoesn'taffectthestandarddescriptorswhichareclosedonlyif:closeisspecifiedexplicitly.

pid=spawn(command,:close_others=>true)#close3,4,5,...(default)

pid=spawn(command,:close_others=>false)#don'tclose3,4,5,...

:close_othersistruebydefaultforspawnandIO.popen.

Notethatfdswhichclose-on-execflagisalreadysetareclosedregardlessof:close_othersoption.

SoIO.pipeandspawncanbeusedasIO.popen.

#similartor=IO.popen(command)

r,w=IO.pipe

pid=spawn(command,:out=>w)#r,wisclosedinthechildprocess.

w.close

:closeisspecifiedasahashvaluetocloseafdindividually.

f=open(foo)

system(command,f=>:close)#don'tinheritf.

Ifafiledescriptorneedtobeinherited,io=>iocanbeused.

#valgrindhas--log-fdoptionforlogdestination.

#log_w=>log_windicateslog_w.filenoinheritstochildprocess.

log_r,log_w=IO.pipe

pid=spawn("valgrind","--log-fd=#{log_w.fileno}","echo"

log_w.close

plog_r.read

Itisalsopossibletoexchangefiledescriptors.

pid=spawn(command,:out=>:err,:err=>:out)

Page 452: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thehashkeysspecifyfiledescriptorsinthechildprocess.Thehashvaluesspecifiesfiledescriptorsintheparentprocess.Sotheabovespecifiesexchangingstdoutandstderr.Internally,spawnusesanextrafiledescriptortoresolvesuchcyclicfiledescriptormapping.

SeeKernel.execforthestandardshell.

Returnsthestringresultingfromapplyingformat_stringtoanyadditionalarguments.Withintheformatstring,anycharactersotherthanformatsequencesarecopiedtotheresult.

Thesyntaxofaformatsequenceisfollows.

%[flags][width][.precision]type

Aformatsequenceconsistsofapercentsign,followedbyoptionalflags,width,andprecisionindicators,thenterminatedwithafieldtypecharacter.Thefieldtypecontrolshowthecorrespondingsprintfargumentistobeinterpreted,whiletheflagsmodifythatinterpretation.

Thefieldtypecharactersare:

Field|IntegerFormat

------+--------------------------------------------------------------

b|Convertargumentasabinarynumber.

|Negativenumberswillbedisplayedasatwo'scomplement

|prefixedwith`..1'.

B|Equivalentto`b',butusesanuppercase0Bforprefix

|inthealternativeformatby#.

d|Convertargumentasadecimalnumber.

format(format_string[,arguments...])→stringsprintf(format_string[,arguments...])→string

Page 453: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

i|Identicalto`d'.

o|Convertargumentasanoctalnumber.

|Negativenumberswillbedisplayedasatwo'scomplement

|prefixedwith`..7'.

u|Identicalto`d'.

x|Convertargumentasahexadecimalnumber.

|Negativenumberswillbedisplayedasatwo'scomplement

|prefixedwith`..f'(representinganinfinitestringof

|leading'ff's).

X|Equivalentto`x',butusesuppercaseletters.

Field|FloatFormat

------+--------------------------------------------------------------

e|Convertfloatingpointargumentintoexponentialnotation

|withonedigitbeforethedecimalpointas[-]d.dddddde[+-]dd.

|Theprecisionspecifiesthenumberofdigitsafterthedecimal

|point(defaultingtosix).

E|Equivalentto`e',butusesanuppercaseEtoindicate

|theexponent.

f|Convertfloatingpointargumentas[-]ddd.dddddd,

|wheretheprecisionspecifiesthenumberofdigitsafter

|thedecimalpoint.

g|Convertafloatingpointnumberusingexponentialform

|iftheexponentislessthan-4orgreaterthanor

|equaltotheprecision,orindd.ddddformotherwise.

|Theprecisionspecifiesthenumberofsignificantdigits.

G|Equivalentto`g',butuseanuppercase`E'inexponentform.

a|Convertfloatingpointargumentas[-]0xh.hhhhp[+-]dd,

|whichisconsistedfromoptionalsign,"0x",fractionpart

|ashexadecimal,"p",andexponentialpartasdecimal.

A|Equivalentto`a',butuseuppercase`X'and`P'.

Field|OtherFormat

------+--------------------------------------------------------------

c|Argumentisthenumericcodeforasinglecharacteror

|asinglecharacterstringitself.

p|Thevaluingofargument.inspect.

s|Argumentisastringtobesubstituted.Iftheformat

|sequencecontainsaprecision,atmostthatmanycharacters

|willbecopied.

%|Apercentsignitselfwillbedisplayed.Noargumenttaken.

Theflagsmodifiesthebehavioroftheformats.Theflagcharactersare:

Flag|Appliesto|Meaning

Page 454: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

---------+---------------+-----------------------------------------

space|bBdiouxX|Leaveaspaceatthestartof

|aAeEfgG|non-negativenumbers.

|(numericfmt)|For`o',`x',`X',`b'and`B',use

||aminussignwithabsolutevaluefor

||negativevalues.

---------+---------------+-----------------------------------------

(digit)$|all|Specifiestheabsoluteargumentnumber

||forthisfield.Absoluteandrelative

||argumentnumberscannotbemixedina

||sprintfstring.

---------+---------------+-----------------------------------------

#|bBoxX|Useanalternativeformat.

|aAeEfgG|Fortheconversions`o',increasetheprecision

||untilthefirstdigitwillbe`0'if

||itisnotformattedascomplements.

||Fortheconversions`x',`X',`b'and`B'

||onnon-zero,prefixtheresultwith``0x'',

||``0X'',``0b''and``0B'',respectively.

||For`a',`A',`e',`E',`f',`g',and'G',

||forceadecimalpointtobeadded,

||evenifnodigitsfollow.

||For`g'and'G',donotremovetrailingzeros.

---------+---------------+-----------------------------------------

+|bBdiouxX|Addaleadingplussigntonon-negative

|aAeEfgG|numbers.

|(numericfmt)|For`o',`x',`X',`b'and`B',use

||aminussignwithabsolutevaluefor

||negativevalues.

---------+---------------+-----------------------------------------

-|all|Left-justifytheresultofthisconversion.

---------+---------------+-----------------------------------------

0(zero)|bBdiouxX|Padwithzeros,notspaces.

|aAeEfgG|For`o',`x',`X',`b'and`B',radix-1

|(numericfmt)|isusedfornegativenumbersformattedas

||complements.

---------+---------------+-----------------------------------------

*|all|Usethenextargumentasthefieldwidth.

||Ifnegative,left-justifytheresult.Ifthe

||asteriskisfollowedbyanumberandadollar

||sign,usetheindicatedargumentasthewidth.

Examplesofflags:

#`+'andspaceflagspecifiesthesignofnon-negativenumbers.

sprintf("%d",123)#=>"123"

Page 455: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

sprintf("%+d",123)#=>"+123"

sprintf("%d",123)#=>"123"

#`#'flagfor`o'increasesnumberofdigitstoshow`0'.

#`+'andspaceflagchangesformatofnegativenumbers.

sprintf("%o",123)#=>"173"

sprintf("%#o",123)#=>"0173"

sprintf("%+o",-123)#=>"-173"

sprintf("%o",-123)#=>"..7605"

sprintf("%#o",-123)#=>"..7605"

#`#'flagfor`x'addaprefix`0x'fornon-zeronumbers.

#`+'andspaceflagdisablescomplementsfornegativenumbers.

sprintf("%x",123)#=>"7b"

sprintf("%#x",123)#=>"0x7b"

sprintf("%+x",-123)#=>"-7b"

sprintf("%x",-123)#=>"..f85"

sprintf("%#x",-123)#=>"0x..f85"

sprintf("%#x",0)#=>"0"

#`#'for`X'usestheprefix`0X'.

sprintf("%X",123)#=>"7B"

sprintf("%#X",123)#=>"0X7B"

#`#'flagfor`b'addaprefix`0b'fornon-zeronumbers.

#`+'andspaceflagdisablescomplementsfornegativenumbers.

sprintf("%b",123)#=>"1111011"

sprintf("%#b",123)#=>"0b1111011"

sprintf("%+b",-123)#=>"-1111011"

sprintf("%b",-123)#=>"..10000101"

sprintf("%#b",-123)#=>"0b..10000101"

sprintf("%#b",0)#=>"0"

#`#'for`B'usestheprefix`0B'.

sprintf("%B",123)#=>"1111011"

sprintf("%#B",123)#=>"0B1111011"

#`#'for`e'forcestoshowthedecimalpoint.

sprintf("%.0e",1)#=>"1e+00"

sprintf("%#.0e",1)#=>"1.e+00"

#`#'for`f'forcestoshowthedecimalpoint.

sprintf("%.0f",1234)#=>"1234"

sprintf("%#.0f",1234)#=>"1234."

#`#'for`g'forcestoshowthedecimalpoint.

#Italsodisablesstrippinglowestzeros.

Page 456: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

sprintf("%g",123.4)#=>"123.4"

sprintf("%#g",123.4)#=>"123.400"

sprintf("%g",123456)#=>"123456"

sprintf("%#g",123456)#=>"123456."

Thefieldwidthisanoptionalinteger,followedoptionallybyaperiodandaprecision.Thewidthspecifiestheminimumnumberofcharactersthatwillbewrittentotheresultforthisfield.

Examplesofwidth:

#paddingisdonebyspaces,width=20

#0orradix-1.<------------------>

sprintf("%20d",123)#=>"123"

sprintf("%+20d",123)#=>"+123"

sprintf("%020d",123)#=>"00000000000000000123"

sprintf("%+020d",123)#=>"+0000000000000000123"

sprintf("%020d",123)#=>"0000000000000000123"

sprintf("%-20d",123)#=>"123"

sprintf("%-+20d",123)#=>"+123"

sprintf("%-20d",123)#=>"123"

sprintf("%020x",-123)#=>"..ffffffffffffffff85"

Fornumericfields,theprecisioncontrolsthenumberofdecimalplacesdisplayed.Forstringfields,theprecisiondeterminesthemaximumnumberofcharacterstobecopiedfromthestring.(Thus,theformatsequence%10.10swillalwayscontributeexactlytencharacterstotheresult.)

Examplesofprecisions:

#precisionfor`d','o','x'and'b'is

#minimumnumberofdigits<------>

sprintf("%20.8d",123)#=>"00000123"

sprintf("%20.8o",123)#=>"00000173"

sprintf("%20.8x",123)#=>"0000007b"

sprintf("%20.8b",123)#=>"01111011"

sprintf("%20.8d",-123)#=>"-00000123"

sprintf("%20.8o",-123)#=>"..777605"

sprintf("%20.8x",-123)#=>"..ffff85"

sprintf("%20.8b",-11)#=>"..110101"

Page 457: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#"0x"and"0b"for`#x'and`#b'isnotcountedfor

#precisionbut"0"for`#o'iscounted.<------>

sprintf("%#20.8d",123)#=>"00000123"

sprintf("%#20.8o",123)#=>"00000173"

sprintf("%#20.8x",123)#=>"0x0000007b"

sprintf("%#20.8b",123)#=>"0b01111011"

sprintf("%#20.8d",-123)#=>"-00000123"

sprintf("%#20.8o",-123)#=>"..777605"

sprintf("%#20.8x",-123)#=>"0x..ffff85"

sprintf("%#20.8b",-11)#=>"0b..110101"

#precisionfor`e'isnumberof

#digitsafterthedecimalpoint<------>

sprintf("%20.8e",1234.56789)#=>"1.23456789e+03"

#precisionfor`f'isnumberof

#digitsafterthedecimalpoint<------>

sprintf("%20.8f",1234.56789)#=>"1234.56789000"

#precisionfor`g'isnumberof

#significantdigits<------->

sprintf("%20.8g",1234.56789)#=>"1234.5679"

#<------->

sprintf("%20.8g",123456789)#=>"1.2345679e+08"

#precisionfor`s'is

#maximumnumberofcharacters<------>

sprintf("%20.8s","stringtest")#=>"stringt"

Examples:

sprintf("%d%04x",123,123)#=>"123007b"

sprintf("%08b'%4s'",123,123)#=>"01111011'123'"

sprintf("%1$*2$s%2$d%1$s","hello",8)#=>"hello8hello"

sprintf("%1$*2$s%2$d","hello",-8)#=>"hello-8"

sprintf("%+g:%g:%-g",1.23,1.23,1.23)#=>"+1.23:1.23:1.23"

sprintf("%u",-123)#=>"-123"

Formorecomplexformatting,Rubysupportsareferencebyname.%<name>sstyleusesformatstyle,but%{name}styledoesn't.

Examples:

Page 458: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

sprintf("%<foo>d:%<bar>f",{:foo=>1,:bar=>2})

#=>1:2.000000

sprintf("%{foo}f",{:foo=>1})

#=>"1f"

Seedsthesystempseudo-randomnumbergenerator,Random::DEFAULT,withnumber.Thepreviousseedvalueisreturned.

Ifnumberisomitted,seedsthegeneratorusingasourceofentropyprovidedbytheoperatingsystem,ifavailable(/dev/urandomonUnixsystemsortheRSAcryptographicprovideronWindows),whichisthencombinedwiththetime,theprocessid,andasequencenumber.

srandmaybeusedtoensurerepeatablesequencesofpseudo-randomnumbersbetweendifferentrunsoftheprogram.Bysettingtheseedtoaknownvalue,programscanbemadedeterministicduringtesting.

srand1234#=>268519324636777531569100071560086917274

[rand,rand]#=>[0.1915194503788923,0.6221087710398319]

[rand(10),rand(1000)]#=>[4,664]

srand1234#=>1234

[rand,rand]#=>[0.1915194503788923,0.6221087710398319]

Equivalentto$_.sub(args),exceptthat$_willbeupdatedifsubstitutionoccurs.Availableonlywhen-p/-ncommandlineoptionspecified.

srand(number=Random.new_seed)→old_seed

sub(pattern,replacement)→$_sub(pattern){|...|block}→$_

Page 459: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Callstheoperatingsystemfunctionidentifiedby_num_and

returnstheresultofthefunctionorraisesSystemCallErrorif

itfailed.

Argumentsforthefunctioncanfollow_num_.Theymustbeeither

+String+objectsor+Integer+objects.A+String+objectispassed

asapointertothebytesequence.An+Integer+objectispassed

asanintegerwhosebitsizeissameasapointer.

Uptonineparametersmaybepassed(14ontheAtari-ST).

Thefunctionidentifiedby_num_issystem

dependent.OnsomeUnixsystems,thenumbersmaybeobtainedfroma

headerfilecalled<code>syscall.h</code>.

syscall4,1,"hello\n",6#'4'iswrite(2)onourbox

<em>produces:</em>

hello

Calling+syscall+onaplatformwhichdoesnothaveanywayto

anarbitrarysystemfunctionjustfailswithNotImplementedError.

Notesyscallisessentiallyunsafeandunportable.Feelfreetoshootyourfoot.DL(Fiddle)libraryispreferredforsaferandabitmoreportableprogramming.

Executescommand…inasubshell.command…isoneoffollowingforms.

commandline:commandlinestringwhichispassedtothestandardshell

cmdname,arg1,...:commandnameandoneormorearguments(noshell)

[cmdname,argv0],arg1,...:commandname,argv[0]andzeroormorearguments(noshell)

syscall(num[,args...])→integer

system([env,]command...[,options])→true,falseornil

Page 460: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

systemreturnstrueifthecommandgiveszeroexitstatus,falsefornonzeroexitstatus.Returnsnilifcommandexecutionfails.Anerrorstatusisavailablein$?.TheargumentsareprocessedinthesamewayasforKernel.spawn.

Thehasharguments,envandoptions,aresameasexecandspawn.SeeKernel.spawnfordetails.

system("echo*")

system("echo","*")

produces:

config.hmain.rb

*

SeeKernel.execforthestandardshell.

Usesthecharactercmdtoperformvarioustestsonfile1(firsttablebelow)oronfile1andfile2(secondtable).

Filetestsonasinglefile:

CmdReturnsMeaning

"A"|Time|Lastaccesstimeforfile1

"b"|boolean|Trueiffile1isablockdevice

"c"|boolean|Trueiffile1isacharacterdevice

"C"|Time|Lastchangetimeforfile1

"d"|boolean|Trueiffile1existsandisadirectory

"e"|boolean|Trueiffile1exists

"f"|boolean|Trueiffile1existsandisaregularfile

"g"|boolean|Trueiffile1hasthe\CF{setgid}bit

||set(falseunderNT)

"G"|boolean|Trueiffile1existsandhasagroup

||ownershipequaltothecaller'sgroup

"k"|boolean|Trueiffile1existsandhasthestickybitset

"l"|boolean|Trueiffile1existsandisasymboliclink

"M"|Time|Lastmodificationtimeforfile1

"o"|boolean|Trueiffile1existsandisownedby

test(cmd,file1[,file2])→obj

Page 461: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

||thecaller'seffectiveuid

"O"|boolean|Trueiffile1existsandisownedby

||thecaller'srealuid

"p"|boolean|Trueiffile1existsandisafifo

"r"|boolean|Trueiffile1isreadablebytheeffective

||uid/gidofthecaller

"R"|boolean|Trueiffileisreadablebythereal

||uid/gidofthecaller

"s"|int/nil|Iffile1hasnonzerosize,returnthesize,

||otherwisereturnnil

"S"|boolean|Trueiffile1existsandisasocket

"u"|boolean|Trueiffile1hasthesetuidbitset

"w"|boolean|Trueiffile1existsandiswritableby

||theeffectiveuid/gid

"W"|boolean|Trueiffile1existsandiswritableby

||therealuid/gid

"x"|boolean|Trueiffile1existsandisexecutableby

||theeffectiveuid/gid

"X"|boolean|Trueiffile1existsandisexecutableby

||therealuid/gid

"z"|boolean|Trueiffile1existsandhasazerolength

Teststhattaketwofiles:

"-"|boolean|Trueiffile1andfile2areidentical

"="|boolean|Trueifthemodificationtimesoffile1

||andfile2areequal

"<"|boolean|Trueifthemodificationtimeoffile1

||ispriortothatoffile2

">"|boolean|Trueifthemodificationtimeoffile1

||isafterthatoffile2

Transferscontroltotheendoftheactivecatchblockwaitingfortag.RaisesUncaughtThrowErrorifthereisnocatchblockforthetag.Theoptionalsecondparametersuppliesareturnvalueforthecatchblock,whichotherwisedefaultstonil.Forexamples,seeKernel::catch.

throw(tag[,obj])

Page 462: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Controlstracingofassignmentstoglobalvariables.Theparametersymbolidentifiesthevariable(aseitherastringnameorasymbolidentifier).cmd(whichmaybeastringoraProcobject)orblockisexecutedwheneverthevariableisassigned.TheblockorProcobjectreceivesthevariable'snewvalueasaparameter.AlsoseeKernel::untrace_var.

trace_var:$_,proc{|v|puts"$_isnow'#{v}'"}

$_="hello"

$_='there'

produces:

$_isnow'hello'

$_isnow'there'

Specifiesthehandlingofsignals.Thefirstparameterisasignalname(astringsuchas“SIGALRM'',“SIGUSR1'',andsoon)orasignalnumber.Thecharacters“SIG''maybeomittedfromthesignalname.Thecommandorblockspecifiescodetoberunwhenthesignalisraised.Ifthecommandisthestring“IGNORE''or“SIG_IGN'',thesignalwillbeignored.Ifthecommandis“DEFAULT''or“SIG_DFL'',theRuby'sdefaulthandlerwillbeinvoked.Ifthecommandis“EXIT'',thescriptwillbeterminatedbythesignal.Ifthecommandis“SYSTEM_DEFAULT'',theoperatingsystem'sdefaulthandlerwillbeinvoked.Otherwise,thegivencommandorblockwillberun.Thespecialsignalname“EXIT''orsignalnumberzerowillbeinvoked

trace_var(symbol,cmd)→niltrace_var(symbol){|val|block}→nil

trap(signal,command)→objtrap(signal){||block}→obj

Page 463: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

justpriortoprogramtermination.trapreturnstheprevioushandlerforthegivensignal.

Signal.trap(0,proc{puts"Terminating:#{$$}"})

Signal.trap("CLD"){puts"Childdied"}

fork&&Process.wait

produces:

Terminating:27461

Childdied

Terminating:27460

Removestracingforthespecifiedcommandonthegivenglobalvariableandreturnsnil.Ifnocommandisspecified,removesalltracingforthatvariableandreturnsanarraycontainingthecommandsactuallyremoved.

DisplayseachofthegivenmessagesfollowedbyarecordseparatoronSTDERRunlesswarningshavebeendisabled(forexamplewiththe-W0flag).

warn("warning1","warning2")

<em>produces:</em>

warning1

warning2

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

untrace_var(symbol[,cmd])→arrayornil

warn(msg,...)→nil

Page 464: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classKeyErrorRaisedwhenthespecifiedkeyisnotfound.ItisasubclassofIndexError.

h={"foo"=>:bar}

h.fetch("foo")#=>:bar

h.fetch("baz")#=>KeyError:keynotfound:"baz"

InFileserror.c

ParentIndexError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 465: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classLoadErrorRaisedwhenafilerequired(aRubyscript,extensionlibrary,…)failstoload.

require'this/file/does/not/exist'

raisestheexception:

LoadError:nosuchfiletoload--this/file/does/not/exist

InFileserror.c

ParentScriptError

Attributes

thepathfailedtoload

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

rb_intern_const("path") [R]

Page 466: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classLocalJumpErrorRaisedwhenRubycan'tyieldasrequested.

Atypicalscenarioisattemptingtoyieldwhennoblockisgiven:

defcall_block

yield42

end

call_block

raisestheexception:

LocalJumpError:noblockgiven(yield)

Amoresubtleexample:

defget_me_a_return

Proc.new{return42}

end

get_me_a_return.call

raisestheexception:

LocalJumpError:unexpectedreturn

InFilesproc.c

Page 467: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ParentStandardError

PublicInstanceMethods

ReturnstheexitvalueassociatedwiththisLocalJumpError.

Thereasonthisblockwasterminated::break,:redo,:retry,:next,:return,or:noreason.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

exit_value→obj

reason→symbol

Page 468: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleMarshalThemarshalinglibraryconvertscollectionsofRubyobjectsintoabytestream,allowingthemtobestoredoutsidethecurrentlyactivescript.Thisdatamaysubsequentlybereadandtheoriginalobjectsreconstituted.

Marshaleddatahasmajorandminorversionnumbersstoredalongwiththeobjectinformation.Innormaluse,marshalingcanonlyloaddatawrittenwiththesamemajorversionnumberandanequalorlowerminorversionnumber.IfRuby's“verbose''flagisset(normallyusing-d,-v,-w,or–verbose)themajorandminornumbersmustmatchexactly.MarshalversioningisindependentofRuby'sversionnumbers.Youcanextracttheversionbyreadingthefirsttwobytesofmarshaleddata.

str=Marshal.dump("thing")

RUBY_VERSION#=>"1.9.0"

str[0].ord#=>4

str[1].ord#=>8

Someobjectscannotbedumped:iftheobjectstobedumpedincludebindings,procedureormethodobjects,instancesofclassIO,orsingletonobjects,aTypeErrorwillberaised.

Ifyourclasshasspecialserializationneeds(for

Page 469: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

example,ifyouwanttoserializeinsomespecificformat),orifitcontainsobjectsthatwouldotherwisenotbeserializable,youcanimplementyourownserializationstrategy.

Therearetwomethodsofdoingthis,yourobjectcandefineeithermarshal_dumpandmarshal_loador_dumpand_load.marshal_dumpwilltakeprecedenceover_dumpifbotharedefined.marshal_dumpmayresultinsmallerMarshalstrings.

Page 470: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Securityconsiderations

Bydesign,::loadcandeserializealmostanyclassloadedintotheRubyprocess.InmanycasesthiscanleadtoremotecodeexecutioniftheMarshaldataisloadedfromanuntrustedsource.

Asaresult,::loadisnotsuitableasageneralpurposeserializationformatandyoushouldneverunmarshalusersuppliedinputorotheruntrusteddata.

Ifyouneedtodeserializeuntrusteddata,useJSONoranotherserializationformatthatisonlyabletoloadsimple,'primitive'typessuchasString,Array,Hash,etc.Neverallowuserinputtospecifyarbitrarytypestodeserializeinto.

Page 471: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

marshal_dumpandmarshal_load

Whendumpinganobjectthemethodmarshal_dumpwillbecalled.marshal_dumpmustreturnaresultcontainingtheinformationnecessaryformarshal_loadtoreconstitutetheobject.Theresultcanbeanyobject.

Whenloadinganobjectdumpedusingmarshal_dumptheobjectisfirstallocatedthenmarshal_loadiscalledwiththeresultfrommarshal_dump.marshal_loadmustrecreatetheobjectfromtheinformationintheresult.

Example:

classMyObj

definitializename,version,data

@name=name

@version=version

@data=data

end

defmarshal_dump

[@name,@version]

end

defmarshal_loadarray

@name,@version=array

end

end

Page 472: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

_dumpand_load

Use_dumpand_loadwhenyouneedtoallocatetheobjectyou'rerestoringyourself.

Whendumpinganobjecttheinstancemethod_dumpiscalledwithanIntegerwhichindicatesthemaximumdepthofobjectstodump(avalueof-1impliesthatyoushoulddisabledepthchecking)._dumpmustreturnaStringcontainingtheinformationnecessarytoreconstitutetheobject.

Theclassmethod_loadshouldtakeaStringanduseittoreturnanobjectofthesameclass.

Example:

classMyObj

definitializename,version,data

@name=name

@version=version

@data=data

end

def_dumplevel

[@name,@version].join':'

end

defself._loadargs

new(*args.split(':'))

end

end

Since::dumpoutputsastringyoucanhave

Page 473: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

_dumpreturnaMarshalstringwhichisMarshal.loadedin_loadforcomplexobjects.

InFilesmarshal.c

Constants

MAJOR_VERSION

majorversion

MINOR_VERSION

minorversion

PublicClassMethods

Serializesobjandalldescendantobjects.IfanIOisspecified,theserializeddatawillbewrittentoit,otherwisethedatawillbereturnedasaString.Iflimitisspecified,thetraversalofsubobjectswillbelimitedtothatdepth.Iflimitisnegative,nocheckingofdepthwillbeperformed.

classKlass

definitialize(str)

@str=str

end

defsay_hello

@str

end

end

dump(obj[,anIO],limit=-1)→anIO

Page 474: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(producesnooutput)

o=Klass.new("hello\n")

data=Marshal.dump(o)

obj=Marshal.load(data)

obj.say_hello#=>"hello\n"

Marshalcan'tdumpfollowingobjects:

anonymousClass/Module.

objectswhicharerelatedtosystem(ex:Dir,File::Stat,IO,File,Socketandsoon)

aninstanceofMatchData,Data,Method,UnboundMethod,Proc,Thread,ThreadGroup,Continuation

objectswhichdefinesingletonmethods

ReturnstheresultofconvertingtheserializeddatainsourceintoaRubyobject(possiblywithassociatedsubordinateobjects).sourcemaybeeitheraninstanceofIOoranobjectthatrespondstoto_str.Ifprocisspecified,eachobjectwillbepassedtotheproc,astheobjectisbeingdeserialized.

Neverpassuntrusteddata(includingusersuppliedinput)tothismethod.Pleaseseetheoverviewforfurtherdetails.

ReturnstheresultofconvertingtheserializeddatainsourceintoaRubyobject(possiblywithassociatedsubordinateobjects).sourcemaybeeitheraninstanceofIOoranobjectthatrespondstoto_str.If

load(source[,proc])→objrestore(source[,proc])→obj

load(source[,proc])→objrestore(source[,proc])→obj

Page 475: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

procisspecified,eachobjectwillbepassedtotheproc,astheobjectisbeingdeserialized.

Neverpassuntrusteddata(includingusersuppliedinput)tothismethod.Pleaseseetheoverviewforfurtherdetails.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 476: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classMatchDataMatchDataisthetypeofthespecialvariable$~,andisthetypeoftheobjectreturnedbyRegexp#matchandRegexp.last_match.Itencapsulatesalltheresultsofapatternmatch,resultsnormallyaccessedthroughthespecialvariables$&,$',$`,$1,$2,andsoon.

InFilesre.c

ParentObject

PublicInstanceMethods

Equality—Twomatchdataareequaliftheirtargetstrings,patterns,andmatchedpositionsareidentical.

mtch==mtch2→trueorfalseeql?(mtch2)→trueorfalse

mtch[i]→strornilmtch[start,length]→arraymtch[range]→arraymtch[name]→strornil

Page 477: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

MatchReference–MatchDataactsasanarray,andmaybeaccessedusingthenormalarrayindexingtechniques.mtch[0]isequivalenttothespecialvariable$&,andreturnstheentirematchedstring.mtch[1],mtch[2],andsoonreturnthevaluesofthematchedbackreferences(portionsofthepatternbetweenparentheses).

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m#=>#<MatchData"HX1138"1:"H"2:"X"3:"113"4:"8">

m[0]#=>"HX1138"

m[1,2]#=>["H","X"]

m[1..3]#=>["H","X","113"]

m[-3,2]#=>["X","113"]

m=/(?<foo>a+)b/.match("ccaaab")

m#=>#<MatchData"aaab"foo:"aaa">

m["foo"]#=>"aaa"

m[:foo]#=>"aaa"

Returnstheoffsetofthestartofthenthelementofthematcharrayinthestring.ncanbeastringorsymboltoreferenceanamedcapture.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.begin(0)#=>1

m.begin(2)#=>2

m=/(?<foo>.)(.)(?<bar>.)/.match("hoge")

pm.begin(:foo)#=>0

pm.begin(:bar)#=>2

Returnsthearrayofcaptures;equivalenttomtch.to_a[1..-1].

f1,f2,f3,f4=/(.)(.)(\d+)(\d)/.match("THX1138.").captures

begin(n)→integer

captures→array

Page 478: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

f1#=>"H"

f2#=>"X"

f3#=>"113"

f4#=>"8"

Returnstheoffsetofthecharacterimmediatelyfollowingtheendofthenthelementofthematcharrayinthestring.ncanbeastringorsymboltoreferenceanamedcapture.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.end(0)#=>7

m.end(2)#=>3

m=/(?<foo>.)(.)(?<bar>.)/.match("hoge")

pm.end(:foo)#=>1

pm.end(:bar)#=>3

Equality—Twomatchdataareequaliftheirtargetstrings,patterns,andmatchedpositionsareidentical.

Produceahashbasedonthetargetstring,regexpandmatchedpositionsofthismatchdata.

SeealsoObject#hash.

Returnsaprintableversionofmtch.

puts/.$/.match("foo").inspect

#=>#<MatchData"o">

end(n)→integer

mtch==mtch2→trueorfalseeql?(mtch2)→trueorfalse

hash→integer

inspect→str

Page 479: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

puts/(.)(.)(.)/.match("foo").inspect

#=>#<MatchData"foo"1:"f"2:"o"3:"o">

puts/(.)(.)?(.)/.match("fo").inspect

#=>#<MatchData"fo"1:"f"2:nil3:"o">

puts/(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge").inspect

#=>#<MatchData"hog"foo:"h"bar:"o"baz:"g">

Returnsthenumberofelementsinthematcharray.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.length#=>5

m.size#=>5

Returnsalistofnamesofcapturesasanarrayofstrings.Itissameasmtch.regexp.names.

/(?<foo>.)(?<bar>.)(?<baz>.)/.match("hoge").names

#=>["foo","bar","baz"]

m=/(?<x>.)(?<y>.)?/.match("a")#=>#<MatchData"a"x:"a"y:nil>

m.names#=>["x","y"]

Returnsatwo-elementarraycontainingthebeginningandendingoffsetsofthenthmatch.ncanbeastringorsymboltoreferenceanamedcapture.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.offset(0)#=>[1,7]

m.offset(4)#=>[6,7]

m=/(?<foo>.)(.)(?<bar>.)/.match("hoge")

length→integersize→integer

names→[name1,name2,...]

offset(n)→array

Page 480: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

pm.offset(:foo)#=>[0,1]

pm.offset(:bar)#=>[2,3]

Returnstheportionoftheoriginalstringafterthecurrentmatch.Equivalenttothespecialvariable$'.

m=/(.)(.)(\d+)(\d)/.match("THX1138:TheMovie")

m.post_match#=>":TheMovie"

Returnstheportionoftheoriginalstringbeforethecurrentmatch.Equivalenttothespecialvariable$`.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.pre_match#=>"T"

Returnstheregexp.

m=/a.*b/.match("abc")

m.regexp#=>/a.*b/

Returnsthenumberofelementsinthematcharray.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.length#=>5

m.size#=>5

Returnsafrozencopyofthestringpassedinto

post_match→str

pre_match→str

regexp→regexp

length→integersize→integer

string→str

Page 481: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

match.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.string#=>"THX1138."

Returnsthearrayofmatches.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.to_a#=>["HX1138","H","X","113","8"]

Becauseto_aiscalledwhenexpanding*variable,there'sausefulassignmentshortcutforextractingmatchedfields.Thisisslightlyslowerthanaccessingthefieldsdirectly(asanintermediatearrayisgenerated).

all,f1,f2,f3=*(/(.)(.)(\d+)(\d)/.match("THX1138."))

all#=>"HX1138"

f1#=>"H"

f2#=>"X"

f3#=>"113"

Returnstheentirematchedstring.

m=/(.)(.)(\d+)(\d)/.match("THX1138.")

m.to_s#=>"HX1138"

Useseachindextoaccessthematchingvalues,returninganarrayofthecorrespondingmatches.

m=/(.)(.)(\d+)(\d)/.match("THX1138:TheMovie")

m.to_a#=>["HX1138","H","X","113","8"]

m.values_at(0,2,-2)#=>["HX1138","X","113"]

to_a→anArray

to_s→str

values_at([index]*)→array

Page 482: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 483: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleMathTheMathmodulecontainsmodulefunctionsforbasictrigonometricandtranscendentalfunctions.SeeclassFloatforalistofconstantsthatdefineRuby'sfloatingpointaccuracy.

Domainsandcodomainsaregivenonlyforreal(notcomplex)numbers.

InFilesmath.c

Constants

E

DefinitionofthemathematicalconstantE(e)asaFloatnumber.

PI

DefinitionofthemathematicalconstantPIasaFloatnumber.

PublicClassMethods

acos(x)→Float

Page 484: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Computesthearccosineofx.Returns0..PI.

Domain:[-1,1]

Codomain:[0,PI]

Math.acos(0)==Math::PI/2#=>true

Computestheinversehyperboliccosineofx.

Domain:[1,INFINITY)

Codomain:[0,INFINITY)

Math.acosh(1)#=>0.0

Computesthearcsineofx.Returns-PI/2..PI/2.

Domain:[-1,-1]

Codomain:[-PI/2,PI/2]

Math.asin(1)==Math::PI/2#=>true

Computestheinversehyperbolicsineofx.

Domain:(-INFINITY,INFINITY)

Codomain:(-INFINITY,INFINITY)

Math.asinh(1)#=>0.881373587019543

Computesthearctangentofx.Returns-PI/2..PI/2.

Domain:(-INFINITY,INFINITY)

acosh(x)→Float

asin(x)→Float

asinh(x)→Float

atan(x)→Float

Page 485: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Codomain:(-PI/2,PI/2)

Math.atan(0)#=>0.0

Computesthearctangentgivenyandx.ReturnsaFloatintherange-PI..PI.

Domain:(-INFINITY,INFINITY)

Codomain:[-PI,PI]

Math.atan2(-0.0,-1.0)#=>-3.141592653589793

Math.atan2(-1.0,-1.0)#=>-2.356194490192345

Math.atan2(-1.0,0.0)#=>-1.5707963267948966

Math.atan2(-1.0,1.0)#=>-0.7853981633974483

Math.atan2(-0.0,1.0)#=>-0.0

Math.atan2(0.0,1.0)#=>0.0

Math.atan2(1.0,1.0)#=>0.7853981633974483

Math.atan2(1.0,0.0)#=>1.5707963267948966

Math.atan2(1.0,-1.0)#=>2.356194490192345

Math.atan2(0.0,-1.0)#=>3.141592653589793

Math.atan2(INFINITY,INFINITY)#=>0.7853981633974483

Math.atan2(INFINITY,-INFINITY)#=>2.356194490192345

Math.atan2(-INFINITY,INFINITY)#=>-0.7853981633974483

Math.atan2(-INFINITY,-INFINITY)#=>-2.356194490192345

Computestheinversehyperbolictangentofx.

Domain:(-1,1)

Codomain:(-INFINITY,INFINITY)

Math.atanh(1)#=>Infinity

Returnsthecuberootofx.

atan2(y,x)→Float

atanh(x)→Float

cbrt(x)→Float

Page 486: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Domain:[0,INFINITY)

Codomain:[0,INFINITY)

-9.upto(9){|x|

p[x,Math.cbrt(x),Math.cbrt(x)**3]

}

#=>[-9,-2.0800838230519,-9.0]

#[-8,-2.0,-8.0]

#[-7,-1.91293118277239,-7.0]

#[-6,-1.81712059283214,-6.0]

#[-5,-1.7099759466767,-5.0]

#[-4,-1.5874010519682,-4.0]

#[-3,-1.44224957030741,-3.0]

#[-2,-1.25992104989487,-2.0]

#[-1,-1.0,-1.0]

#[0,0.0,0.0]

#[1,1.0,1.0]

#[2,1.25992104989487,2.0]

#[3,1.44224957030741,3.0]

#[4,1.5874010519682,4.0]

#[5,1.7099759466767,5.0]

#[6,1.81712059283214,6.0]

#[7,1.91293118277239,7.0]

#[8,2.0,8.0]

#[9,2.0800838230519,9.0]

Computesthecosineofx(expressedinradians).ReturnsaFloatintherange-1.0..1.0.

Domain:(-INFINITY,INFINITY)

Codomain:[-1,1]

Math.cos(Math::PI)#=>-1.0

Computesthehyperboliccosineofx(expressedinradians).

Domain:(-INFINITY,INFINITY)

cos(x)→Float

cosh(x)→Float

Page 487: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Codomain:[1,INFINITY)

Math.cosh(0)#=>1.0

Calculatestheerrorfunctionofx.

Domain:(-INFINITY,INFINITY)

Codomain:(-1,1)

Math.erf(0)#=>0.0

Calculatesthecomplementaryerrorfunctionofx.

Domain:(-INFINITY,INFINITY)

Codomain:(0,2)

Math.erfc(0)#=>1.0

Returnse**x.

Domain:(-INFINITY,INFINITY)

Codomain:(0,INFINITY)

Math.exp(0)#=>1.0

Math.exp(1)#=>2.718281828459045

Math.exp(1.5)#=>4.4816890703380645

Returnsatwo-elementarraycontainingthenormalizedfraction(aFloat)andexponent(aFixnum)ofx.

erf(x)→Float

erfc(x)→Float

exp(x)→Float

frexp(x)→[fraction,exponent]

Page 488: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

fraction,exponent=Math.frexp(1234)#=>[0.6025390625,11]

fraction*2**exponent#=>1234.0

Calculatesthegammafunctionofx.

Notethatgamma(n)issameasfact(n-1)forintegern>0.Howevergamma(n)returnsfloatandcanbeanapproximation.

deffact(n)(1..n).inject(1){|r,i|r*i}end

1.upto(26){|i|p[i,Math.gamma(i),fact(i-1)]}

#=>[1,1.0,1]

#[2,1.0,1]

#[3,2.0,2]

#[4,6.0,6]

#[5,24.0,24]

#[6,120.0,120]

#[7,720.0,720]

#[8,5040.0,5040]

#[9,40320.0,40320]

#[10,362880.0,362880]

#[11,3628800.0,3628800]

#[12,39916800.0,39916800]

#[13,479001600.0,479001600]

#[14,6227020800.0,6227020800]

#[15,87178291200.0,87178291200]

#[16,1307674368000.0,1307674368000]

#[17,20922789888000.0,20922789888000]

#[18,355687428096000.0,355687428096000]

#[19,6.402373705728e+15,6402373705728000]

#[20,1.21645100408832e+17,121645100408832000]

#[21,2.43290200817664e+18,2432902008176640000]

#[22,5.109094217170944e+19,51090942171709440000]

#[23,1.1240007277776077e+21,1124000727777607680000]

#[24,2.5852016738885062e+22,25852016738884976640000]

#[25,6.204484017332391e+23,620448401733239439360000]

#[26,1.5511210043330954e+25,15511210043330985984000000]

gamma(x)→Float

hypot(x,y)→Float

Page 489: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnssqrt(x**2+y**2),thehypotenuseofaright-angledtrianglewithsidesxandy.

Math.hypot(3,4)#=>5.0

Returnsthevalueoffraction*(2**exponent).

fraction,exponent=Math.frexp(1234)

Math.ldexp(fraction,exponent)#=>1234.0

Calculatesthelogarithmicgammaofxandthesignofgammaofx.

::lgammaissameas

[Math.log(Math.gamma(x).abs),Math.gamma(x)<0?-1:1]

butavoidoverflowby::gammaforlargex.

Math.lgamma(0)#=>[Infinity,1]

Returnsthelogarithmofx.Ifadditionalsecondargumentisgiven,itwillbethebaseoflogarithm.Otherwiseitise(forthenaturallogarithm).

Domain:(0,INFINITY)

Codomain:(-INFINITY,INFINITY)

Math.log(0)#=>-Infinity

Math.log(1)#=>0.0

Math.log(Math::E)#=>1.0

Math.log(Math::E**3)#=>3.0

ldexp(fraction,exponent)→float

lgamma(x)→[float,-1or1]

log(x)→Floatlog(x,base)→Float

Page 490: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Math.log(12,3)#=>2.2618595071429146

Returnsthebase10logarithmofx.

Domain:(0,INFINITY)

Codomain:(-INFINITY,INFINITY)

Math.log10(1)#=>0.0

Math.log10(10)#=>1.0

Math.log10(10**100)#=>100.0

Returnsthebase2logarithmofx.

Domain:(0,INFINITY)

Codomain:(-INFINITY,INFINITY)

Math.log2(1)#=>0.0

Math.log2(2)#=>1.0

Math.log2(32768)#=>15.0

Math.log2(65536)#=>16.0

Computesthesineofx(expressedinradians).ReturnsaFloatintherange-1.0..1.0.

Domain:(-INFINITY,INFINITY)

Codomain:[-1,1]

Math.sin(Math::PI/2)#=>1.0

Computesthehyperbolicsineofx(expressedinradians).

log10(x)→Float

log2(x)→Float

sin(x)→Float

sinh(x)→Float

Page 491: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Domain:(-INFINITY,INFINITY)

Codomain:(-INFINITY,INFINITY)

Math.sinh(0)#=>0.0

Returnsthenon-negativesquarerootofx.

Domain:[0,INFINITY)

Codomain:[0,INFINITY)

0.upto(10){|x|

p[x,Math.sqrt(x),Math.sqrt(x)**2]

}

#=>[0,0.0,0.0]

#[1,1.0,1.0]

#[2,1.4142135623731,2.0]

#[3,1.73205080756888,3.0]

#[4,2.0,4.0]

#[5,2.23606797749979,5.0]

#[6,2.44948974278318,6.0]

#[7,2.64575131106459,7.0]

#[8,2.82842712474619,8.0]

#[9,3.0,9.0]

#[10,3.16227766016838,10.0]

Computesthetangentofx(expressedinradians).

Domain:(-INFINITY,INFINITY)

Codomain:(-INFINITY,INFINITY)

Math.tan(0)#=>0.0

Computesthehyperbolictangentofx(expressedinradians).

sqrt(x)→Float

tan(x)→Float

tanh(x)→Float

Page 492: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Domain:(-INFINITY,INFINITY)

Codomain:(-1,1)

Math.tanh(0)#=>0.0

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 493: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classMath::DomainErrorRaisedwhenamathematicalfunctionisevaluatedoutsideofitsdomainofdefinition.

Forexample,sincecosreturnsvaluesintherange-1..1,itsinversefunctionacosisonlydefinedonthatinterval:

Math.acos(42)

produces:

Math::DomainError:Numericalargumentisoutofdomain-"acos"

InFilesmath.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 494: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classMethodProc

InFilesproc.c

ParentObject

PublicInstanceMethods

Twomethodobjectsareequaliftheyareboundtothesameobjectandrefertothesamemethoddefinitionandtheirownersarethesameclassormodule.

Invokesthemethwiththespecifiedarguments,returningthemethod'sreturnvalue.

m=12.method("+")

m.call(3)#=>15

m.call(20)#=>32

eql?(other_meth)→trueorfalsemeth==other_meth→trueorfalse

call(args,...)→objmeth[args,...]→obj

Page 495: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanindicationofthenumberofargumentsacceptedbyamethod.Returnsanonnegativeintegerformethodsthattakeafixednumberofarguments.ForRubymethodsthattakeavariablenumberofarguments,returns-n-1,wherenisthenumberofrequiredarguments.FormethodswritteninC,returns-1ifthecalltakesavariablenumberofarguments.

classC

defone;end

deftwo(a);end

defthree(*a);end

deffour(a,b);end

deffive(a,b,*c);end

defsix(a,b,*c,&d);end

end

c=C.new

c.method(:one).arity#=>0

c.method(:two).arity#=>1

c.method(:three).arity#=>-1

c.method(:four).arity#=>2

c.method(:five).arity#=>-3

c.method(:six).arity#=>-3

"cat".method(:size).arity#=>0

"cat".method(:replace).arity#=>1

"cat".method(:squeeze).arity#=>-1

"cat".method(:count).arity#=>-1

Invokesthemethwiththespecifiedarguments,returningthemethod'sreturnvalue.

m=12.method("+")

m.call(3)#=>15

m.call(20)#=>32

arity→fixnum

call(args,...)→objmeth[args,...]→obj

Page 496: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsacloneofthismethod.

classA

deffoo

return"bar"

end

end

m=A.new.method(:foo)

m.call#=>"bar"

n=m.clone.call#=>"bar"

Returnsacurriedprocbasedonthemethod.Whentheprociscalledwithanumberofargumentsthatislowerthanthemethod'sarity,thenanothercurriedprocisreturned.Onlywhenenoughargumentshavebeensuppliedtosatisfythemethodsignature,willthemethodactuallybecalled.

Theoptionalarityargumentshouldbesuppliedwhencurryingmethodswithvariableargumentstodeterminehowmanyargumentsareneededbeforethemethodiscalled.

deffoo(a,b,c)

[a,b,c]

end

proc=self.method(:foo).curry

proc2=proc.call(1,2)#=>#<Proc>

proc2.call(3)#=>[1,2,3]

defvararg(*args)

args

end

proc=self.method(:vararg).curry(4)

proc2=proc.call(:x)#=>#<Proc>

clone→new_method

curry→proccurry(arity)→proc

Page 497: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

proc3=proc2.call(:y,:z)#=>#<Proc>

proc3.call(:a)#=>[:x,:y,:z,:a]

Twomethodobjectsareequaliftheyareboundtothesameobjectandrefertothesamemethoddefinitionandtheirownersarethesameclassormodule.

Returnsahashvaluecorrespondingtothemethodobject.

SeealsoObject#hash.

Returnsthenameoftheunderlyingmethod.

"cat".method(:count).inspect#=>"#<Method:String#count>"

Returnsthenameofthemethod.

Returnstheoriginalnameofthemethod.

Returnstheclassormodulethatdefinesthemethod.

eql?(other_meth)→trueorfalsemeth==other_meth→trueorfalse

hash→integer

to_s→stringinspect→string

name→symbol

original_name→symbol

owner→class_or_module

Page 498: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheparameterinformationofthismethod.

Returnstheboundreceiverofthemethodobject.

ReturnstheRubysourcefilenameandlinenumbercontainingthismethodornilifthismethodwasnotdefinedinRuby(i.e.native)

ReturnsaMethodofsuperclass,whichwouldbecalledwhensuperisused.

ReturnsaProcobjectcorrespondingtothismethod.

Returnsthenameoftheunderlyingmethod.

"cat".method(:count).inspect#=>"#<Method:String#count>"

Dissociatesmethfromitscurrentreceiver.TheresultingUnboundMethodcansubsequentlybeboundtoanewobjectofthesameclass(seeUnboundMethod).

parameters→array

receiver→object

source_location→[String,Fixnum]

super_method()

to_proc→proc

to_s→stringinspect→string

unbind→unbound_method

Page 499: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 500: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classModuleAModuleisacollectionofmethodsandconstants.Themethodsinamodulemaybeinstancemethodsormodulemethods.Instancemethodsappearasmethodsinaclasswhenthemoduleisincluded,modulemethodsdonot.Conversely,modulemethodsmaybecalledwithoutcreatinganencapsulatingobject,whileinstancemethodsmaynot.(SeeModule#module_function.)

Inthedescriptionsthatfollow,theparametersymreferstoasymbol,whichiseitheraquotedstringoraSymbol(suchas:name).

moduleMod

includeMath

CONST=1

defmeth

#...

end

end

Mod.class#=>Module

Mod.constants#=>[:CONST,:PI,:E]

Mod.instance_methods#=>[:meth]

InFilesclass.ceval.cload.c

Page 501: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

object.cproc.cvm_eval.cvm_method.c

ParentObject

PublicClassMethods

Inthefirstform,returnsanarrayofthenamesofallconstantsaccessiblefromthepointofcall.Thislistincludesthenamesofallmodulesandclassesdefinedintheglobalscope.

Module.constants.first(4)

#=>[:ARGF,:ARGV,:ArgumentError,:Array]

Module.constants.include?(:SEEK_SET)#=>false

classIO

Module.constants.include?(:SEEK_SET)#=>true

end

Thesecondformcallstheinstancemethodconstants.

ReturnsthelistofModulesnestedatthepointofcall.

moduleM1

moduleM2

$a=Module.nesting

constants→arrayconstants(inherited)→array

nesting→array

Page 502: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

end

$a#=>[M1::M2,M1]

$a[0].name#=>"M1::M2"

Createsanewanonymousmodule.Ifablockisgiven,itispassedthemoduleobject,andtheblockisevaluatedinthecontextofthismoduleusingmodule_eval.

fred=Module.newdo

defmeth1

"hello"

end

defmeth2

"bye"

end

end

a="mystring"

a.extend(fred)#=>"mystring"

a.meth1#=>"hello"

a.meth2#=>"bye"

Assignthemoduletoaconstant(namestartinguppercase)ifyouwanttotreatitlikearegularmodule.

PublicInstanceMethods

Returnstrueifmodisasubclassofother.Returnsnilifthere'snorelationshipbetweenthetwo.(Thinkoftherelationshipintermsoftheclassdefinition:“classA<B”implies“A<B”.)

new→modnew{|mod|block}→mod

mod<other→true,false,ornil

Page 503: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifmodisasubclassofotheroristhesameasother.Returnsnilifthere'snorelationshipbetweenthetwo.(Thinkoftherelationshipintermsoftheclassdefinition:“classA<B”implies“A<B”.)

Comparison—Returns-1,0,+1ornildependingonwhethermoduleincludesother_module,theyarethesame,orifmoduleisincludedbyother_module.ThisisthebasisforthetestsinComparable.

Returnsnilifmodulehasnorelationshipwithother_module,ifother_moduleisnotamodule,orifthetwovaluesareincomparable.

Equality—AttheObjectlevel,==returnstrueonlyifobjandotherarethesameobject.Typically,thismethodisoverriddenindescendantclassestoprovideclass-specificmeaning.

Unlike==,theequal?methodshouldneverbeoverriddenbysubclassesasitisusedtodetermineobjectidentity(thatis,a.equal?(b)ifandonlyifaisthesameobjectasb):

obj="a"

other=obj.dup

obj==other#=>true

obj.equal?other#=>false

obj.equal?obj#=>true

mod<=other→true,false,ornil

module<=>other_module→-1,0,+1,ornil

obj==other→trueorfalseequal?(other)→trueorfalseeql?(other)→trueorfalse

Page 504: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Theeql?methodreturnstrueifobjandotherrefertothesamehashkey.ThisisusedbyHashtotestmembersforequality.ForobjectsofclassObject,eql?issynonymouswith==.Subclassesnormallycontinuethistraditionbyaliasingeql?totheiroverridden==method,butthereareexceptions.Numerictypes,forexample,performtypeconversionacross==,butnotacrosseql?,so:

1==1.0#=>true

1.eql?1.0#=>false

CaseEquality—Returnstrueifobjisaninstanceofmodoroneofmod'sdescendants.Oflimiteduseformodules,butcanbeusedincasestatementstoclassifyobjectsbyclass.

Returnstrueifmodisanancestorofother.Returnsnilifthere'snorelationshipbetweenthetwo.(Thinkoftherelationshipintermsoftheclassdefinition:“classA<B”implies“B>A”.)

Returnstrueifmodisanancestorofother,orthetwomodulesarethesame.Returnsnilifthere'snorelationshipbetweenthetwo.(Thinkoftherelationshipintermsoftheclassdefinition:“classA<B”implies“B>A”.)

mod===obj→trueorfalse

mod>other→true,false,ornil

mod>=other→true,false,ornil

ancestors→array

Page 505: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsalistofmodulesincluded/prependedinmod(includingmoditself).

moduleMod

includeMath

includeComparable

prependEnumerable

end

Mod.ancestors#=>[Enumerable,Mod,Comparable,Math]

Math.ancestors#=>[Math]

Enumerable.ancestors#=>[Enumerable]

Registersfilenametobeloaded(usingKernel::require)thefirsttimethatmodule(whichmaybeaStringorasymbol)isaccessedinthenamespaceofmod.

moduleA

end

A.autoload(:B,"b")

A::B.doit#autoloads"b"

Returnsfilenametobeloadedifnameisregisteredasautoloadinthenamespaceofmod.

moduleA

end

A.autoload(:B,"b")

A.autoload?(:B)#=>"b"

autoload(module,filename)→nil

autoload?(name)→Stringornil

class_eval(string[,filename[,lineno]])→objmodule_eval{||block}→obj

Page 506: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Evaluatesthestringorblockinthecontextofmod,exceptthatwhenablockisgiven,constant/classvariablelookupisnotaffected.Thiscanbeusedtoaddmethodstoaclass.module_evalreturnstheresultofevaluatingitsargument.Theoptionalfilenameandlinenoparameterssetthetextforerrormessages.

classThing

end

a=%q{defhello()"Hellothere!"end}

Thing.module_eval(a)

putsThing.new.hello()

Thing.module_eval("invalidcode","dummy",123)

produces:

Hellothere!

dummy:123:in`module_eval':undefinedlocalvariable

ormethod`code'forThing:Class

Evaluatesthegivenblockinthecontextoftheclass/module.Themethoddefinedintheblockwillbelongtothereceiver.Anyargumentspassedtothemethodwillbepassedtotheblock.Thiscanbeusediftheblockneedstoaccessinstancevariables.

classThing

end

Thing.class_exec{

defhello()"Hellothere!"end

}

putsThing.new.hello()

produces:

Hellothere!

module_exec(arg...){|var...|block}→objclass_exec(arg...){|var...|block}→obj

Page 507: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthegivenclassvariableisdefinedinobj.Stringargumentsareconvertedtosymbols.

classFred

@@foo=99

end

Fred.class_variable_defined?(:@@foo)#=>true

Fred.class_variable_defined?(:@@bar)#=>false

Returnsthevalueofthegivenclassvariable(orthrowsaNameErrorexception).The@@partofthevariablenameshouldbeincludedforregularclassvariables.Stringargumentsareconvertedtosymbols.

classFred

@@foo=99

end

Fred.class_variable_get(:@@foo)#=>99

Setstheclassvariablenamedbysymboltothegivenobject.Iftheclassvariablenameispassedasastring,thatstringisconvertedtoasymbol.

classFred

@@foo=99

deffoo

class_variable_defined?(symbol)→trueorfalseclass_variable_defined?(string)→trueorfalse

class_variable_get(symbol)→objclass_variable_get(string)→obj

class_variable_set(symbol,obj)→objclass_variable_set(string,obj)→obj

Page 508: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

@@foo

end

end

Fred.class_variable_set(:@@foo,101)#=>101

Fred.new.foo#=>101

Returnsanarrayofthenamesofclassvariablesinmod.Thisincludesthenamesofclassvariablesinanyincludedmodules,unlesstheinheritparameterissettofalse.

classOne

@@var1=1

end

classTwo<One

@@var2=2

end

One.class_variables#=>[:@@var1]

Two.class_variables#=>[:@@var2,:@@var1]

Two.class_variables(false)#=>[:@@var2]

Sayswhethermodoritsancestorshaveaconstantwiththegivenname:

Float.const_defined?(:EPSILON)#=>true,foundinFloatitself

Float.const_defined?("String")#=>true,foundinObject(ancestor)

BasicObject.const_defined?(:Hash)#=>false

IfmodisaModule,additionallyObjectanditsancestorsarechecked:

Math.const_defined?(:String)#=>true,foundinObject

class_variables(inherit=true)→array

const_defined?(sym,inherit=true)→trueorfalseconst_defined?(str,inherit=true)→trueorfalse

Page 509: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ineachofthecheckedclassesormodules,iftheconstantisnotpresentbutthereisanautoloadforit,trueisreturneddirectlywithoutautoloading:

moduleAdmin

autoload:User,'admin/user'

end

Admin.const_defined?(:User)#=>true

Iftheconstantisnotfoundthecallbackconst_missingisnotcalledandthemethodreturnsfalse.

Ifinheritisfalse,thelookuponlycheckstheconstantsinthereceiver:

IO.const_defined?(:SYNC)#=>true,foundinFile::Constants(ancestor)

IO.const_defined?(:SYNC,false)#=>false,notfoundinIOitself

Inthiscase,thesamelogicforautoloadingapplies.

IftheargumentisnotavalidconstantnameaNameErrorisraisedwiththemessage“wrongconstantnamename”:

Hash.const_defined?'foobar'#=>NameError:wrongconstantnamefoobar

Checksforaconstantwiththegivennameinmod.Ifinheritisset,thelookupwillalsosearchtheancestors(andObjectifmodisaModule).

Thevalueoftheconstantisreturnedifadefinitionisfound,otherwiseaNameErrorisraised.

Math.const_get(:PI)#=>3.14159265358979

const_get(sym,inherit=true)→objconst_get(str,inherit=true)→obj

Page 510: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thismethodwillrecursivelylookupconstantnamesifanamespacedclassnameisprovided.Forexample:

moduleFoo;classBar;endend

Object.const_get'Foo::Bar'

Theinheritflagisrespectedoneachlookup.Forexample:

moduleFoo

classBar

VAL=10

end

classBaz<Bar;end

end

Object.const_get'Foo::Baz::VAL'#=>10

Object.const_get'Foo::Baz::VAL',false#=>NameError

IftheargumentisnotavalidconstantnameaNameErrorwillberaisedwithawarning“wrongconstantname”.

Object.const_get'foobar'#=>NameError:wrongconstantnamefoobar

Invokedwhenareferenceismadetoanundefinedconstantinmod.Itispassedasymbolfortheundefinedconstant,andreturnsavaluetobeusedforthatconstant.Thefollowingcodeisanexampleofthesame:

defFoo.const_missing(name)

name#returntheconstantnameasSymbol

end

Foo::UNDEFINED_CONST#=>:UNDEFINED_CONST:symbolreturned

const_missing(sym)→obj

Page 511: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Inthenextexamplewhenareferenceismadetoanundefinedconstant,itattemptstoloadafilewhosenameisthelowercaseversionoftheconstant(thusclassFredisassumedtobeinfilefred.rb).Iffound,itreturnstheloadedclass.ItthereforeimplementsanautoloadfeaturesimilartoKernel#autoloadand#autoload.

defObject.const_missing(name)

@looked_for||={}

str_name=name.to_s

raise"Classnotfound:#{name}"if@looked_for[str_name

@looked_for[str_name]=1

file=str_name.downcase

requirefile

klass=const_get(name)

returnklassifklass

raise"Classnotfound:#{name}"

end

Setsthenamedconstanttothegivenobject,returningthatobject.Createsanewconstantifnoconstantwiththegivennamepreviouslyexisted.

Math.const_set("HIGH_SCHOOL_PI",22.0/7.0)#=>3.14285714285714

Math::HIGH_SCHOOL_PI-Math::PI#=>0.00126448926734968

IfsymorstrisnotavalidconstantnameaNameErrorwillberaisedwithawarning“wrongconstantname”.

Object.const_set('foobar',42)#=>NameError:wrongconstantnamefoobar

const_set(sym,obj)→objconst_set(str,obj)→obj

constants(inherit=true)→array

Page 512: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanarrayofthenamesoftheconstantsaccessibleinmod.Thisincludesthenamesofconstantsinanyincludedmodules(exampleatstartofsection),unlesstheinheritparameterissettofalse.

IO.constants.include?(:SYNC)#=>true

IO.constants(false).include?(:SYNC)#=>false

AlsoseeModule::const_defined?.

Preventsfurthermodificationstomod.

Thismethodreturnsself.

InvokesModule.append_featuresoneachparameterinreverseorder.

Returnstrueifmoduleisincludedinmodoroneofmod'sancestors.

moduleA

end

classB

includeA

end

classC<B

end

B.include?(A)#=>true

C.include?(A)#=>true

A.include?(A)#=>false

Returnsthelistofmodulesincludedinmod.

freeze→mod

include(module,...)→self

include?(module)→trueorfalse

included_modules→array

Page 513: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleMixin

end

moduleOuter

includeMixin

end

Mixin.included_modules#=>[]

Outer.included_modules#=>[Mixin]

Aliasfor:to_s

ReturnsanUnboundMethodrepresentingthegiveninstancemethodinmod.

classInterpreter

defdo_a()print"there,";end

defdo_d()print"Hello";end

defdo_e()print"!\n";end

defdo_v()print"Dave";end

Dispatcher={

"a"=>instance_method(:do_a),

"d"=>instance_method(:do_d),

"e"=>instance_method(:do_e),

"v"=>instance_method(:do_v)

}

definterpret(string)

string.each_char{|b|Dispatcher[b].bind(self).call

end

end

interpreter=Interpreter.new

interpreter.interpret('dave')

produces:

Hellothere,Dave!

inspect()

instance_method(symbol)→unbound_method

Page 514: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsanarraycontainingthenamesofthepublicandprotectedinstancemethodsinthereceiver.Foramodule,thesearethepublicandprotectedmethods;foraclass,theyaretheinstance(notsingleton)methods.Iftheoptionalparameterisfalse,themethodsofanyancestorsarenotincluded.

moduleA

defmethod1()end

end

classB

includeA

defmethod2()end

end

classC<B

defmethod3()end

end

A.instance_methods(false)#=>[:method1]

B.instance_methods(false)#=>[:method2]

B.instance_methods(true).include?(:method1)#=>true

C.instance_methods(false)#=>[:method3]

C.instance_methods.include?(:method2)#=>true

Returnstrueifthenamedmethodisdefinedbymod(oritsincludedmodulesand,ifmodisaclass,itsancestors).Publicandprotectedmethodsarematched.Stringargumentsareconvertedtosymbols.

moduleA

defmethod1()end

end

classB

defmethod2()end

instance_methods(include_super=true)→array

method_defined?(symbol)→trueorfalsemethod_defined?(string)→trueorfalse

Page 515: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

classC<B

includeA

defmethod3()end

end

A.method_defined?:method1#=>true

C.method_defined?"method1"#=>true

C.method_defined?"method2"#=>true

C.method_defined?"method3"#=>true

C.method_defined?"method4"#=>false

Evaluatesthestringorblockinthecontextofmod,exceptthatwhenablockisgiven,constant/classvariablelookupisnotaffected.Thiscanbeusedtoaddmethodstoaclass.module_evalreturnstheresultofevaluatingitsargument.Theoptionalfilenameandlinenoparameterssetthetextforerrormessages.

classThing

end

a=%q{defhello()"Hellothere!"end}

Thing.module_eval(a)

putsThing.new.hello()

Thing.module_eval("invalidcode","dummy",123)

produces:

Hellothere!

dummy:123:in`module_eval':undefinedlocalvariable

ormethod`code'forThing:Class

class_eval(string[,filename[,lineno]])→objmodule_eval{||block}→obj

module_exec(arg...){|var...|block}→objclass_exec(arg...){|var...|block}→obj

Page 516: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Evaluatesthegivenblockinthecontextoftheclass/module.Themethoddefinedintheblockwillbelongtothereceiver.Anyargumentspassedtothemethodwillbepassedtotheblock.Thiscanbeusediftheblockneedstoaccessinstancevariables.

classThing

end

Thing.class_exec{

defhello()"Hellothere!"end

}

putsThing.new.hello()

produces:

Hellothere!

Returnsthenameofthemodulemod.Returnsnilforanonymousmodules.

InvokesModule.prepend_featuresoneachparameterinreverseorder.

Makesexistingclassmethodsprivate.Oftenusedtohidethedefaultconstructornew.

Stringargumentsareconvertedtosymbols.

classSimpleSingleton#Notthreadsafe

private_class_method:new

defSimpleSingleton.create(*args,&block)

@me=new(*args,&block)if!@me

@me

end

name→string

prepend(module,...)→self

private_class_method(symbol,...)→modprivate_class_method(string,...)→mod

Page 517: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

Makesalistofexistingconstantsprivate.

Returnsalistoftheprivateinstancemethodsdefinedinmod.Iftheoptionalparameterisfalse,themethodsofanyancestorsarenotincluded.

moduleMod

defmethod1()end

private:method1

defmethod2()end

end

Mod.instance_methods#=>[:method2]

Mod.private_instance_methods#=>[:method1]

Returnstrueifthenamedprivatemethodisdefinedby_mod_(oritsincludedmodulesand,ifmodisaclass,itsancestors).Stringargumentsareconvertedtosymbols.

moduleA

defmethod1()end

end

classB

private

defmethod2()end

end

classC<B

includeA

private_constant(symbol,...)→mod

private_instance_methods(include_super=true)→array

private_method_defined?(symbol)→trueorfalseprivate_method_defined?(string)→trueorfalse

Page 518: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

defmethod3()end

end

A.method_defined?:method1#=>true

C.private_method_defined?"method1"#=>false

C.private_method_defined?"method2"#=>true

C.method_defined?"method2"#=>false

Returnsalistoftheprotectedinstancemethodsdefinedinmod.Iftheoptionalparameterisfalse,themethodsofanyancestorsarenotincluded.

Returnstrueifthenamedprotectedmethodisdefinedbymod(oritsincludedmodulesand,ifmodisaclass,itsancestors).Stringargumentsareconvertedtosymbols.

moduleA

defmethod1()end

end

classB

protected

defmethod2()end

end

classC<B

includeA

defmethod3()end

end

A.method_defined?:method1#=>true

C.protected_method_defined?"method1"#=>false

C.protected_method_defined?"method2"#=>true

C.method_defined?"method2"#=>true

protected_instance_methods(include_super=true)→array

protected_method_defined?(symbol)→trueorfalseprotected_method_defined?(string)→trueorfalse

Page 519: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Makesalistofexistingclassmethodspublic.

Stringargumentsareconvertedtosymbols.

Makesalistofexistingconstantspublic.

Similarto#instance_method,searchespublicmethodonly.

Returnsalistofthepublicinstancemethodsdefinedinmod.Iftheoptionalparameterisfalse,themethodsofanyancestorsarenotincluded.

Returnstrueifthenamedpublicmethodisdefinedbymod(oritsincludedmodulesand,ifmodisaclass,itsancestors).Stringargumentsareconvertedtosymbols.

moduleA

defmethod1()end

end

public_class_method(symbol,...)→modpublic_class_method(string,...)→mod

public_constant(symbol,...)→mod

public_instance_method(symbol)→unbound_method

public_instance_methods(include_super=true)→array

public_method_defined?(symbol)→trueorfalsepublic_method_defined?(string)→trueorfalse

Page 520: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classB

protected

defmethod2()end

end

classC<B

includeA

defmethod3()end

end

A.method_defined?:method1#=>true

C.public_method_defined?"method1"#=>true

C.public_method_defined?"method2"#=>false

C.method_defined?"method2"#=>true

Removesthedefinitionofthesym,returningthatconstant'svalue.

classDummy

@@var=99

puts@@var

remove_class_variable(:@@var)

p(defined?@@var)

end

produces:

99

nil

Returnstrueifmodisasingletonclassorfalseifitisanordinaryclassormodule.

classC

end

C.singleton_class?#=>false

C.singleton_class.singleton_class?#=>true

remove_class_variable(sym)→obj

singleton_class?→trueorfalse

to_s→string

Page 521: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsastringrepresentingthismoduleorclass.Forbasicclassesandmodules,thisisthename.Forsingletons,weshowinformationonthethingwe'reattachedtoaswell.

Alsoaliasedas:inspect

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 522: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classMutexMuteximplementsasimplesemaphorethatcanbeusedtocoordinateaccesstoshareddatafrommultipleconcurrentthreads.

Example:

require'thread'

semaphore=Mutex.new

a=Thread.new{

semaphore.synchronize{

#accesssharedresource

}

}

b=Thread.new{

semaphore.synchronize{

#accesssharedresource

}

}

InFilesthread.c

ParentObject

PublicClassMethods

Page 523: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CreatesanewMutex

PublicInstanceMethods

Attemptstograbthelockandwaitsifitisn'tavailable.RaisesThreadErrorifmutexwaslockedbythecurrentthread.

Returnstrueifthislockiscurrentlyheldbysomethread.

Returnstrueifthislockiscurrentlyheldbycurrentthread.ThisAPIisexperimental,andsubjecttochange.

Releasesthelockandsleepstimeoutsecondsifitisgivenandnon-nilorforever.RaisesThreadErrorifmutexwasn'tlockedbythecurrentthread.

Whenthethreadisnextwokenup,itwillattempttoreacquirethelock.

NotethatthismethodcanwakeupwithoutexplicitThread#wakeupcall.Forexample,receivingsignalandsoon.

new→mutex

lock→self

locked?→trueorfalse

owned?→trueorfalse

sleep(timeout=nil)→number

Page 524: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Obtainsalock,runstheblock,andreleasesthelockwhentheblockcompletes.SeetheexampleunderMutex.

Attemptstoobtainthelockandreturnsimmediately.Returnstrueifthelockwasgranted.

Releasesthelock.RaisesThreadErrorifmutexwasn'tlockedbythecurrentthread.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

synchronize{...}→resultoftheblock

try_lock→trueorfalse

unlock→self

Page 525: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classNameErrorRaisedwhenagivennameisinvalidorundefined.

putsfoo

raisestheexception:

NameError:undefinedlocalvariableormethod`foo'formain:Object

Sinceconstantnamesmuststartwithacapital:

Fixnum.const_set:answer,42

raisestheexception:

NameError:wrongconstantnameanswer

InFileserror.c

ParentStandardError

PublicClassMethods

Page 526: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ConstructanewNameErrorexception.IfgiventhenameparametermaysubsequentlybeexaminedusingtheNameError.namemethod.

PublicInstanceMethods

ReturnthenameassociatedwiththisNameErrorexception.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

new(msg[,name])→name_error

name→stringornil

Page 527: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classNilClassTheclassofthesingletonobjectnil.

InFilescomplex.cobject.crational.c

ParentObject

PublicInstanceMethods

And—Returnsfalse.objisalwaysevaluatedasitistheargumenttoamethodcall—thereisnoshort-circuitevaluationinthiscase.

ExclusiveOr—Ifobjisnilorfalse,returnsfalse;otherwise,returnstrue.

false&obj→falsenil&obj→false

false^obj→trueorfalsenil^obj→trueorfalse

inspect→"nil"

Page 528: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Alwaysreturnsthestring“nil”.

Onlytheobjectnilrespondstruetonil?.

Returnszeroasarational.Theoptionalargumentepsisalwaysignored.

Alwaysreturnsanemptyarray.

nil.to_a#=>[]

Returnszeroasacomplex.

Alwaysreturnszero.

nil.to_f#=>0.0

Alwaysreturnsanemptyhash.

nil.to_h#=>{}

Alwaysreturnszero.

nil.to_i#=>0

nil?→true

rationalize([eps])→(0/1)

to_a→[]

to_c→(0+0i)

to_f→0.0

to_h→{}

to_i→0

Page 529: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnszeroasarational.

Alwaysreturnstheemptystring.

Or—Returnsfalseifobjisnilorfalse;trueotherwise.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

to_r→(0/1)

to_s→""

false|obj→trueorfalsenil|obj→trueorfalse

Page 530: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classNoMemoryErrorRaisedwhenmemoryallocationfails.

InFileserror.c

ParentException

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 531: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classNoMethodErrorRaisedwhenamethodiscalledonareceiverwhichdoesn'thaveitdefinedandalsofailstorespondwithmethod_missing.

"hello".to_ary

raisestheexception:

NoMethodError:undefinedmethod`to_ary'for"hello":String

InFileserror.c

ParentNameError

PublicClassMethods

ConstructaNoMethodErrorexceptionforamethodofthegivennamecalledwiththegivenarguments.Thenamemaybeaccessedusingthe#namemethodontheresultingobject,andtheargumentsusingthe#argsmethod.

new(msg,name[,args])→no_method_error

Page 532: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PublicInstanceMethods

Returntheargumentspassedinasthethirdparametertotheconstructor.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

args→obj

Page 533: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classNotImplementedErrorRaisedwhenafeatureisnotimplementedonthecurrentplatform.Forexample,methodsdependingonthefsyncorforksystemcallsmayraisethisexceptioniftheunderlyingoperatingsystemorRubyruntimedoesnotsupportthem.

NotethatifforkraisesaNotImplementedError,thenrespond_to?(:fork)returnsfalse.

InFileserror.c

ParentScriptError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 534: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classNumericThetop-levelnumberclass.

InFilescomplex.cnumeric.crational.c

ParentObject

IncludedModulesComparable

PublicInstanceMethods

x.modulo(y)meansx-y*(x/y).floor

Equivalenttonum.divmod(numeric)[1].

See#divmod.

UnaryPlus—Returnsthereceiver'svalue.

modulo(numeric)→real

+num→num

Page 535: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

UnaryMinus—Returnsthereceiver'svalue,negated.

Returnszeroifnumberequalsother,otherwisenilisreturnedifthetwovaluesareincomparable.

Returnstheabsolutevalueofnum.

12.abs#=>12

(-34.56).abs#=>34.56

-34.56.abs#=>34.56

#magnitudeisanaliasof#abs.

Returnssquareofself.

Returns0ifthevalueispositive,piotherwise.

Returns0ifthevalueispositive,piotherwise.

-num→numeric

number<=>other→0ornil

abs→numericmagnitude→numeric

abs2→real

arg→0orfloatangle→0orfloatphase→0orfloat

arg→0orfloatangle→0orfloatphase→0orfloat

ceil→integer

Page 536: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsthesmallestpossibleIntegerthatisgreaterthanorequaltonum.

NumericachievesthisbyconvertingitselftoaFloattheninvokingFloat#ceil.

1.ceil#=>1

1.2.ceil#=>2

(-1.2).ceil#=>-1

(-1.0).ceil#=>-1

Ifa+numericisthesametypeasnum,returnsanarraycontainingnumericandnum.Otherwise,returnsanarraywithbothanumericandnumrepresentedasFloatobjects.

ThiscoercionmechanismisusedbyRubytohandlemixed-typenumericoperations:itisintendedtofindacompatiblecommontypebetweenthetwooperandsoftheoperator.

1.coerce(2.5)#=>[2.5,1.0]

1.2.coerce(3)#=>[3.0,1.2]

1.coerce(2)#=>[2,1]

Returnsself.

Returnsself.

coerce(numeric)→array

conj→selfconjugate→self

conj→selfconjugate→self

denominator→integer

Page 537: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthedenominator(alwayspositive).

Uses/toperformdivision,thenconvertstheresulttoaninteger.numericdoesnotdefinethe/operator;thisislefttosubclasses.

Equivalenttonum.divmod(numeric)[0].

See#divmod.

Returnsanarraycontainingthequotientandmodulusobtainedbydividingnumbynumeric.

Ifq,r=*x.divmod(y),then

q=floor(x/y)

x=q*y+r

Thequotientisroundedtoward-infinity,asshowninthefollowingtable:

a|b|a.divmod(b)|a/b|a.modulo(b)|a.remainder(b)

------+-----+---------------+---------+-------------+---------------

13|4|3,1|3|1|1

------+-----+---------------+---------+-------------+---------------

13|-4|-4,-3|-4|-3|1

------+-----+---------------+---------+-------------+---------------

-13|4|-4,3|-4|3|-1

------+-----+---------------+---------+-------------+---------------

-13|-4|3,-1|3|-1|-1

------+-----+---------------+---------+-------------+---------------

11.5|4|2,3.5|2.875|3.5|3.5

------+-----+---------------+---------+-------------+---------------

11.5|-4|-3,-0.5|-2.875|-0.5|3.5

------+-----+---------------+---------+-------------+---------------

-11.5|4|-3,0.5|-2.875|0.5|-3.5

------+-----+---------------+---------+-------------+---------------

-11.5|-4|2,-3.5|2.875|-3.5|-3.5

div(numeric)→integer

divmod(numeric)→array

Page 538: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Examples

11.divmod(3)#=>[3,2]

11.divmod(-3)#=>[-4,-1]

11.divmod(3.5)#=>[3,0.5]

(-11).divmod(3.5)#=>[-4,3.0]

(11.5).divmod(3.5)#=>[3,1.0]

Returnstrueifnumandnumericarethesametypeandhaveequalvalues.

1==1.0#=>true

1.eql?(1.0)#=>false

(1.0).eql?(1.0)#=>true

Returnsfloatdivision.

Returnsthelargestintegerlessthanorequaltonum.

NumericimplementsthisbyconvertinganIntegertoaFloatandinvokingFloat#floor.

1.floor#=>1

(-1).floor#=>-1

Returnsthecorrespondingimaginarynumber.Notavailableforcomplexnumbers.

Returnszero.

eql?(numeric)→trueorfalse

fdiv(numeric)→float

floor→integer

i→Complex(0,num)

imag→0imaginary→0

Page 539: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnszero.

Numericsareimmutablevalues,whichshouldnotbecopied.

AnyattempttousethismethodonaNumericwillraiseaTypeError.

ReturnstrueifnumisanInteger(includingFixnumandBignum).

(1.0).integer?#=>false

(1).integer?#=>true

Returnstheabsolutevalueofnum.

12.abs#=>12

(-34.56).abs#=>34.56

-34.56.abs#=>34.56

#magnitudeisanaliasof#abs.

x.modulo(y)meansx-y*(x/y).floor

Equivalenttonum.divmod(numeric)[1].

imag→0imaginary→0

initialize_copy(p1)

integer?→trueorfalse

abs→numericmagnitude→numeric

modulo(numeric)→real

Page 540: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

See#divmod.

Returnsselfifnumisnotzero,nilotherwise.

Thisbehaviorisusefulwhenchainingcomparisons:

a=%w(zBbbBbbBBaaAAaAAA)

b=a.sort{|a,b|(a.downcase<=>b.downcase).nonzero?

b#=>["A","a","AA","Aa","aA","BB","Bb","bB","bb","z"]

Returnsthenumerator.

Returns0ifthevalueispositive,piotherwise.

Returnsanarray;[num.abs,num.arg].

Returnsmostexactdivision(rationalforintegers,floatforfloats).

Returnsself.

nonzero?→selfornil

numerator→integer

arg→0orfloatangle→0orfloatphase→0orfloat

polar→array

quo(int_or_rat)→ratquo(flo)→flo

real→self

real?→trueorfalse

Page 541: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstrueifnumisaRealnumber.(i.e.notComplex).

Returnsanarray;[num,0].

Returnsanarray;[num,0].

x.remainder(y)meansx-y*(x/y).truncate

See#divmod.

Roundsnumtoagivenprecisionindecimaldigits(default0digits).

Precisionmaybenegative.Returnsafloatingpointnumberwhenndigitsismorethanzero.

NumericimplementsthisbyconvertingitselftoaFloatandinvokingFloat#round.

TrapattemptstoaddmethodstoNumericobjects.AlwaysraisesaTypeError.

Numericsshouldbevalues;singleton_methodsshouldnotbeaddedtothem.

rect→arrayrectangular→array

rect→arrayrectangular→array

remainder(numeric)→real

round([ndigits])→integerorfloat

singleton_method_added(p1)

Page 542: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Invokesthegivenblockwiththesequenceofnumbersstartingatnum,incrementedbystep(defaultedto1)oneachcall.

Theloopfinisheswhenthevaluetobepassedtotheblockisgreaterthanlimit(ifstepispositive)orlessthanlimit(ifstepisnegative),wherelimitisdefaultedtoinfinity.

Intherecommendedkeywordargumentstyle,eitherorbothofstepandlimit(defaultinfinity)canbeomitted.Inthefixedpositionargumentstyle,zeroasastep(i.e.num.step(limit,0))isnotallowedforhistoricalcompatibilityreasons.

Ifalltheargumentsareintegers,theloopoperatesusinganintegercounter.

Ifanyoftheargumentsarefloatingpointnumbers,allareconvertedtofloats,andtheloopisexecutedthefollowingexpression:

floor(n+n*epsilon)+1

Wherethenisthefollowing:

n=(limit-num)/step

Otherwise,theloopstartsatnum,useseithertheless-than(<)orgreater-than(>)operatortocomparethecounteragainstlimit,andincrementsitselfusingthe+operator.

Ifnoblockisgiven,anEnumeratorisreturnedinstead.

step(by:step,to:limit){|i|block}→selfstep(by:step,to:limit)→an_enumeratorstep(limit=nil,step=1){|i|block}→selfstep(limit=nil,step=1)→an_enumerator

Page 543: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Forexample:

p1.step.take(4)

p10.step(by:-1).take(4)

3.step(to:5){|i|printi,""}

1.step(10,2){|i|printi,""}

Math::E.step(to:Math::PI,by:0.2){|f|printf,""

Willproduce:

[1,2,3,4]

[10,9,8,7]

345

13579

2.718281828459052.918281828459053.11828182845905

Returnsthevalueasacomplex.

Invokesthechildclass'sto_imethodtoconvertnumtoaninteger.

1.0.class=>Float

1.0.to_int.class=>Fixnum

1.0.to_i.class=>Fixnum

ReturnsnumtruncatedtoanInteger.

NumericimplementsthisbyconvertingitsvaluetoaFloatandinvokingFloat#truncate.

Returnstrueifnumhasazerovalue.

to_c→complex

to_int→integer

truncate→integer

zero?→trueorfalse

Page 544: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 545: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classObjectObjectisthedefaultrootofallRubyobjects.ObjectinheritsfromBasicObjectwhichallowscreatingalternateobjecthierarchies.MethodsonObjectareavailabletoallclassesunlessexplicitlyoverridden.

ObjectmixesintheKernelmodule,makingthebuilt-inkernelfunctionsgloballyaccessible.AlthoughtheinstancemethodsofObjectaredefinedbytheKernelmodule,wehavechosentodocumentthemhereforclarity.

WhenreferencingconstantsinclassesinheritingfromObjectyoudonotneedtousethefullnamespace.Forexample,referencingFileinsideYourClasswillfindthetop-levelFileclass.

InthedescriptionsofObject'smethods,theparametersymbolreferstoasymbol,whichiseitheraquotedstringoraSymbol(suchas:name).

InFilesclass.cenumerator.ceval.cgc.chash.c

Page 546: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

io.cobject.cparse.cproc.cruby.cversion.cvm.cvm_eval.cvm_method.c

ParentBasicObject

IncludedModulesKernel

Constants

ARGF

ARGFisastreamdesignedforuseinscriptsthatprocessfilesgivenascommand-lineargumentsorpassedinviaSTDIN.

SeeARGF(theclass)formoredetails.

ARGV

ARGVcontainsthecommandlineargumentsusedtorunrubywiththefirstvaluecontainingthenameoftheexecutable.

AlibrarylikeOptionParsercanbeusedtoprocesscommand-linearguments.

Page 547: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

DATA

DATAisaFilethatcontainsthedatasectionoftheexecutedfile.Tocreateadatasectionuse__END__:

$catt.rb

putsDATA.gets

__END__

helloworld!

$rubyt.rb

helloworld!

ENV

ENVisaHash-likeaccessorforenvironmentvariables.

SeeENV(theclass)formoredetails.

FALSE

Analiasoffalse

NIL

Analiasofnil

RUBY_COPYRIGHT

Thecopyrightstringforruby

RUBY_DESCRIPTION

Thefullrubyversionstring,likeruby-vprints'

RUBY_ENGINE

Theengineorinterpreterthisrubyuses.

RUBY_PATCHLEVEL

Page 548: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thepatchlevelforthisruby.Ifthisisadevelopmentbuildofrubythepatchlevelwillbe-1

RUBY_PLATFORM

Theplatformforthisruby

RUBY_RELEASE_DATE

Thedatethisrubywasreleased

RUBY_REVISION

TheSVNrevisionforthisruby.

RUBY_VERSION

Therunningversionofruby

SCRIPT_LINES__

WhenaHashisassignedtoSCRIPT_LINES__thecontentsoffilesloadedaftertheassignmentwillbeaddedasanArrayoflineswiththefilenameasthekey.

STDERR

Holdstheoriginalstderr

STDIN

Holdstheoriginalstdin

STDOUT

Holdstheoriginalstdout

TOPLEVEL_BINDING

TheBindingofthetoplevelscope

Page 549: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

TRUE

Analiasoftrue

PublicInstanceMethods

Returnstrueiftwoobjectsdonotmatch(usingthe=~method),otherwisefalse.

Returns0ifobjandotherarethesameobjectorobj==other,otherwisenil.

The<=>isusedbyvariousmethodstocompareobjects,forexampleEnumerable#sort,Enumerable#maxetc.

Yourimplementationof<=>shouldreturnoneofthefollowingvalues:-1,0,1ornil.-1meansselfissmallerthanother.0meansselfisequaltoother.1meansselfisbiggerthanother.Nilmeansthetwovaluescouldnotbecompared.

Whenyoudefine<=>,youcanincludeComparabletogainthemethods<=,<,==,>=,>andbetween?.

CaseEquality–ForclassObject,effectivelythesameascalling#==,buttypicallyoverriddenbydescendantstoprovidemeaningfulsemanticsincasestatements.

obj!~other→trueorfalse

obj<=>other→0ornil

obj===other→trueorfalse

obj=~other→nil

Page 550: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PatternMatch—Overriddenbydescendants(notablyRegexpandString)toprovidemeaningfulpattern-matchsemantics.

Returnstheclassofobj.Thismethodmustalwaysbecalledwithanexplicitreceiver,asclassisalsoareservedwordinRuby.

1.class#=>Fixnum

self.class#=>Object

Producesashallowcopyofobj—theinstancevariablesofobjarecopied,butnottheobjectstheyreference.clonecopiesthefrozenandtaintedstateofobj.SeealsothediscussionunderObject#dup.

classKlass

attr_accessor:str

end

s1=Klass.new#=>#<Klass:0x401b3a38>

s1.str="Hello"#=>"Hello"

s2=s1.clone#=>#<Klass:0x401b3998@str="Hello">

s2.str[1,4]="i"#=>"i"

s1.inspect#=>"#<Klass:0x401b3a38@str=\"Hi\">"

s2.inspect#=>"#<Klass:0x401b3998@str=\"Hi\">"

Thismethodmayhaveclass-specificbehavior.Ifso,thatbehaviorwillbedocumentedunderthe#initialize_copymethodoftheclass.

class→class

clone→an_object

define_singleton_method(symbol,method)→new_methoddefine_singleton_method(symbol){block}

Page 551: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Definesasingletonmethodinthereceiver.ThemethodparametercanbeaProc,aMethodoranUnboundMethodobject.Ifablockisspecified,itisusedasthemethodbody.

classA

class<<self

defclass_name

to_s

end

end

end

A.define_singleton_method(:who_am_i)do

"Iam:#{class_name}"

end

A.who_am_i#==>"Iam:A"

guy="Bob"

guy.define_singleton_method(:hello){"#{self}:Hellothere!"

guy.hello#=>"Bob:Hellothere!"

Printsobjonthegivenport(default$>).Equivalentto:

defdisplay(port=$>)

port.writeself

end

Forexample:

1.display

"cat".display

[4,5,6].display

puts

produces:

1cat456

→proc

display(port=$>)→nil

Page 552: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Producesashallowcopyofobj—theinstancevariablesofobjarecopied,butnottheobjectstheyreference.dupcopiesthetaintedstateofobj.

Thismethodmayhaveclass-specificbehavior.Ifso,thatbehaviorwillbedocumentedunderthe#initialize_copymethodoftheclass.

ondupvscloneIngeneral,cloneanddupmayhavedifferentsemanticsindescendantclasses.Whilecloneisusedtoduplicateanobject,includingitsinternalstate,duptypicallyusestheclassofthedescendantobjecttocreatethenewinstance.

Whenusingdup,anymodulesthattheobjecthasbeenextendedwithwillnotbecopied.

classKlass

attr_accessor:str

end

moduleFoo

deffoo;'foo';end

end

s1=Klass.new#=>#<Klass:0x401b3a38>

s1.extend(Foo)#=>#<Klass:0x401b3a38>

s1.foo#=>"foo"

s2=s1.clone#=>#<Klass:0x401b3a38>

s2.foo#=>"foo"

s3=s1.dup#=>#<Klass:0x401b3a38>

s3.foo#=>NoMethodError:undefinedmethod`foo'for#<Klass:0x401b3a38>

dup→an_object

to_enum(method=:each,*args)→enum

Page 553: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CreatesanewEnumeratorwhichwillenumeratebycallingmethodonobj,passingargsifany.

Ifablockisgiven,itwillbeusedtocalculatethesizeoftheenumeratorwithouttheneedtoiterateit(seeEnumerator#size).

Examplesstr="xyz"

enum=str.enum_for(:each_byte)

enum.each{|b|putsb}

#=>120

#=>121

#=>122

#protectanarrayfrombeingmodifiedbysome_method

a=[1,2,3]

some_method(a.to_enum)

Itistypicaltocall#to_enumwhendefiningmethodsforagenericEnumerable,incasenoblockispassed.

Hereissuchanexample,withparameterpassingandasizingblock:

moduleEnumerable

#agenericmethodtorepeatthevaluesofanyenumerable

defrepeat(n)

raiseArgumentError,"#{n}isnegative!"ifn<0

unlessblock_given?

returnto_enum(__method__,n)do#__method__is:repeathere

sz=size#Callsizeandmultiplybyn...

sz*nifsz#butreturnnilifsizeitselfisnil

end

enum_for(method=:each,*args)→enumto_enum(method=:each,*args){|*args|block}→enumenum_for(method=:each,*args){|*args|block}→enum

Page 554: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

eachdo|*val|

n.times{yield*val}

end

end

end

%[helloworld].repeat(2){|w|putsw}

#=>Prints'hello','hello','world','world'

enum=(1..14).repeat(3)

#=>returnsanEnumeratorwhencalledwithoutablock

enum.first(4)#=>[1,1,1,2]

enum.size#=>42

Equality—AttheObjectlevel,==returnstrueonlyifobjandotherarethesameobject.Typically,thismethodisoverriddenindescendantclassestoprovideclass-specificmeaning.

Unlike==,theequal?methodshouldneverbeoverriddenbysubclassesasitisusedtodetermineobjectidentity(thatis,a.equal?(b)ifandonlyifaisthesameobjectasb):

obj="a"

other=obj.dup

obj==other#=>true

obj.equal?other#=>false

obj.equal?obj#=>true

Theeql?methodreturnstrueifobjandotherrefertothesamehashkey.ThisisusedbyHashtotestmembersforequality.ForobjectsofclassObject,eql?issynonymouswith==.Subclassesnormallycontinuethistraditionbyaliasingeql?totheir

obj==other→trueorfalseequal?(other)→trueorfalseeql?(other)→trueorfalse

Page 555: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

overridden==method,butthereareexceptions.Numerictypes,forexample,performtypeconversionacross==,butnotacrosseql?,so:

1==1.0#=>true

1.eql?1.0#=>false

Addstoobjtheinstancemethodsfromeachmodulegivenasaparameter.

moduleMod

defhello

"HellofromMod.\n"

end

end

classKlass

defhello

"HellofromKlass.\n"

end

end

k=Klass.new

k.hello#=>"HellofromKlass.\n"

k.extend(Mod)#=>#<Klass:0x401b3bc8>

k.hello#=>"HellofromMod.\n"

Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.

Thismethodreturnsself.

a=["a","b","c"]

a.freeze

a<<"z"

extend(module,...)→obj

freeze→obj

Page 556: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

produces:

prog.rb:3:in`<<':can'tmodifyfrozenArray(RuntimeError)

fromprog.rb:3

Objectsofthefollowingclassesarealwaysfrozen:Fixnum,Bignum,Float,Symbol.

Returnsthefreezestatusofobj.

a=["a","b","c"]

a.freeze#=>["a","b","c"]

a.frozen?#=>true

GeneratesaFixnumhashvalueforthisobject.Thisfunctionmusthavethepropertythata.eql?(b)impliesa.hash==b.hash.

Thehashvalueisusedalongwitheql?bytheHashclasstodetermineiftwoobjectsreferencethesamehashkey.AnyhashvaluethatexceedsthecapacityofaFixnumwillbetruncatedbeforebeingused.

ThehashvalueforanobjectmaynotbeidenticalacrossinvocationsorimplementationsofRuby.IfyouneedastableidentifieracrossRubyinvocationsandimplementationsyouwillneedtogenerateonewithacustommethod.

Returnsastringcontainingahuman-readablerepresentationofobj.Thedefaultinspectshowstheobject'sclassname,anencodingoftheobjectid,andalistoftheinstancevariablesandtheirvalues(by

frozen?→trueorfalse

hash→fixnum

inspect→string

Page 557: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

callinginspectoneachofthem).Userdefinedclassesshouldoverridethismethodtoprovideabetterrepresentationofobj.Whenoverridingthismethod,itshouldreturnastringwhoseencodingiscompatiblewiththedefaultexternalencoding.

[1,2,3..4,'five'].inspect#=>"[1,2,3..4,\"five\"]"

Time.new.inspect#=>"2008-03-0819:43:39+0900"

classFoo

end

Foo.new.inspect#=>"#<Foo:0x0300c868>"

classBar

definitialize

@bar=1

end

end

Bar.new.inspect#=>"#<Bar:0x0300c868@bar=1>"

Returnstrueifobjisaninstanceofthegivenclass.SeealsoObject#kind_of?.

classA;end

classB<A;end

classC<B;end

b=B.new

b.instance_of?A#=>false

b.instance_of?B#=>true

b.instance_of?C#=>false

Returnstrueifthegiveninstancevariableisdefined

instance_of?(class)→trueorfalse

instance_variable_defined?(symbol)→trueorfalseinstance_variable_defined?(string)→trueorfalse

Page 558: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

inobj.Stringargumentsareconvertedtosymbols.

classFred

definitialize(p1,p2)

@a,@b=p1,p2

end

end

fred=Fred.new('cat',99)

fred.instance_variable_defined?(:@a)#=>true

fred.instance_variable_defined?("@b")#=>true

fred.instance_variable_defined?("@c")#=>false

Returnsthevalueofthegiveninstancevariable,orniliftheinstancevariableisnotset.The@partofthevariablenameshouldbeincludedforregularinstancevariables.ThrowsaNameErrorexceptionifthesuppliedsymbolisnotvalidasaninstancevariablename.Stringargumentsareconvertedtosymbols.

classFred

definitialize(p1,p2)

@a,@b=p1,p2

end

end

fred=Fred.new('cat',99)

fred.instance_variable_get(:@a)#=>"cat"

fred.instance_variable_get("@b")#=>99

Setstheinstancevariablenamedbysymboltothegivenobject,therebyfrustratingtheeffortsoftheclass'sauthortoattempttoprovideproperencapsulation.Thevariabledoesnothavetoexistpriortothiscall.Iftheinstancevariablenameis

instance_variable_get(symbol)→objinstance_variable_get(string)→obj

instance_variable_set(symbol,obj)→objinstance_variable_set(string,obj)→obj

Page 559: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

passedasastring,thatstringisconvertedtoasymbol.

classFred

definitialize(p1,p2)

@a,@b=p1,p2

end

end

fred=Fred.new('cat',99)

fred.instance_variable_set(:@a,'dog')#=>"dog"

fred.instance_variable_set(:@c,'cat')#=>"cat"

fred.inspect#=>"#<Fred:0x401b3da8@a=\"dog\",@b=99,@c=\"cat\">"

Returnsanarrayofinstancevariablenamesforthereceiver.Notethatsimplydefininganaccessordoesnotcreatethecorrespondinginstancevariable.

classFred

attr_accessor:a1

definitialize

@iv=3

end

end

Fred.new.instance_variables#=>[:@iv]

Returnstrueifclassistheclassofobj,orifclassisoneofthesuperclassesofobjormodulesincludedinobj.

moduleM;end

classA

includeM

end

classB<A;end

classC<B;end

instance_variables→array

is_a?(class)→trueorfalsekind_of?(class)→trueorfalse

Page 560: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

b=B.new

b.is_a?A#=>true

b.is_a?B#=>true

b.is_a?C#=>false

b.is_a?M#=>true

b.kind_of?A#=>true

b.kind_of?B#=>true

b.kind_of?C#=>false

b.kind_of?M#=>true

Returnsobj.

string='mystring'#=>"mystring"

string.itself.object_id==string.object_id#=>true

Returnstrueifclassistheclassofobj,orifclassisoneofthesuperclassesofobjormodulesincludedinobj.

moduleM;end

classA

includeM

end

classB<A;end

classC<B;end

b=B.new

b.is_a?A#=>true

b.is_a?B#=>true

b.is_a?C#=>false

b.is_a?M#=>true

b.kind_of?A#=>true

b.kind_of?B#=>true

b.kind_of?C#=>false

b.kind_of?M#=>true

itself→an_object

is_a?(class)→trueorfalsekind_of?(class)→trueorfalse

Page 561: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Looksupthenamedmethodasareceiverinobj,returningaMethodobject(orraisingNameError).TheMethodobjectactsasaclosureinobj'sobjectinstance,soinstancevariablesandthevalueofselfremainavailable.

classDemo

definitialize(n)

@iv=n

end

defhello()

"Hello,@iv=#{@iv}"

end

end

k=Demo.new(99)

m=k.method(:hello)

m.call#=>"Hello,@iv=99"

l=Demo.new('Fred')

m=l.method("hello")

m.call#=>"Hello,@iv=Fred"

Returnsalistofthenamesofpublicandprotectedmethodsofobj.Thiswillincludeallthemethodsaccessibleinobj'sancestors.Iftheoptionalparameterisfalse,itreturnsanarrayofobj<i>'spublicandprotectedsingletonmethods,thearraywillnotincludemethodsinmodulesincludedin<i>obj.

classKlass

defklass_method()

end

end

k=Klass.new

k.methods[0..9]#=>[:klass_method,:nil?,:===,

#:==~,:!,:eql?

method(sym)→method

methods(regular=true)→array

Page 562: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#:hash,:<=>,:class,:singleton_class]

k.methods.length#=>56

k.methods(false)#=>[]

defk.singleton_method;end

k.methods(false)#=>[:singleton_method]

moduleM123;defm123;endend

k.extendM123

k.methods(false)#=>[:singleton_method]

Onlytheobjectnilrespondstruetonil?.

Object.new.nil?#=>false

nil.nil?#=>true

Returnsanintegeridentifierforobj.

Thesamenumberwillbereturnedonallcallstoobject_idforagivenobject,andnotwoactiveobjectswillshareanid.

Note:thatsomeobjectsofbuiltinclassesarereusedforoptimization.Thisisthecaseforimmediatevaluesandfrozenstringliterals.

Immediatevaluesarenotpassedbyreferencebutarepassedbyvalue:nil,true,false,Fixnums,Symbols,andsomeFloats.

Object.new.object_id==Object.new.object_id#=>false

(21*2).object_id==(21*2).object_id#=>true

"hello".object_id=="hello".object_id#=>false

"hi".freeze.object_id=="hi".freeze.object_id#=>true

nil?→trueorfalse

__id__→integerobject_id→integer

Page 563: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthelistofprivatemethodsaccessibletoobj.Iftheallparameterissettofalse,onlythosemethodsinthereceiverwillbelisted.

Returnsthelistofprotectedmethodsaccessibletoobj.Iftheallparameterissettofalse,onlythosemethodsinthereceiverwillbelisted.

Similartomethod,searchespublicmethodonly.

Returnsthelistofpublicmethodsaccessibletoobj.Iftheallparameterissettofalse,onlythosemethodsinthereceiverwillbelisted.

Invokesthemethodidentifiedbysymbol,passingitanyargumentsspecified.Unlikesend,#public_sendcallspublicmethodsonly.Whenthemethodisidentifiedbyastring,thestringisconvertedtoasymbol.

1.public_send(:puts,"hello")#causesNoMethodError

Removesthenamedinstancevariablefromobj,returningthatvariable'svalue.

private_methods(all=true)→array

protected_methods(all=true)→array

public_method(sym)→method

public_methods(all=true)→array

public_send(symbol[,args...])→objpublic_send(string[,args...])→obj

remove_instance_variable(symbol)→obj

Page 564: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classDummy

attr_reader:var

definitialize

@var=99

end

defremove

remove_instance_variable(:@var)

end

end

d=Dummy.new

d.var#=>99

d.remove#=>99

d.var#=>nil

Returnstrueifobjrespondstothegivenmethod.Privateandprotectedmethodsareincludedinthesearchonlyiftheoptionalsecondparameterevaluatestotrue.

Ifthemethodisnotimplemented,asProcess.forkonWindows,File.lchmodonGNU/Linux,etc.,falseisreturned.

Ifthemethodisnotdefined,respond_to_missing?methodiscalledandtheresultisreturned.

Whenthemethodnameparameterisgivenasastring,thestringisconvertedtoasymbol.

DONOTUSETHISDIRECTLY.

respond_to?(symbol,include_all=false)→trueorfalserespond_to?(string,include_all=false)→trueorfalse

respond_to_missing?(symbol,include_all)→trueorfalserespond_to_missing?(string,include_all)→trueorfalse

Page 565: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Hookmethodtoreturnwhethertheobjcanrespondtoidmethodornot.

Whenthemethodnameparameterisgivenasastring,thestringisconvertedtoasymbol.

Seerespond_to?,andtheexampleofBasicObject.

Invokesthemethodidentifiedbysymbol,passingitanyargumentsspecified.Youcanuse__send__ifthenamesendclasheswithanexistingmethodinobj.Whenthemethodisidentifiedbyastring,thestringisconvertedtoasymbol.

classKlass

defhello(*args)

"Hello"+args.join('')

end

end

k=Klass.new

k.send:hello,"gentle","readers"#=>"Hellogentlereaders"

Returnsthesingletonclassofobj.Thismethodcreatesanewsingletonclassifobjdoesnothaveone.

Ifobjisnil,true,orfalse,itreturnsNilClass,TrueClass,orFalseClass,respectively.IfobjisaFixnumoraSymbol,itraisesaTypeError.

Object.new.singleton_class#=>#<Class:#<Object:0xb7ce1e24>>

String.singleton_class#=>#<Class:String>

nil.singleton_class#=>NilClass

send(symbol[,args...])→obj__send__(symbol[,args...])→objsend(string[,args...])→obj__send__(string[,args...])→obj

singleton_class→class

Page 566: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Similartomethod,searchessingletonmethodonly.

classDemo

definitialize(n)

@iv=n

end

defhello()

"Hello,@iv=#{@iv}"

end

end

k=Demo.new(99)

defk.hi

"Hi,@iv=#{@iv}"

end

m=k.singleton_method(:hi)

m.call#=>"Hi,@iv=99"

m=k.singleton_method(:hello)#=>NameError

Returnsanarrayofthenamesofsingletonmethodsforobj.Iftheoptionalallparameteristrue,thelistwillincludemethodsinmodulesincludedinobj.Onlypublicandprotectedsingletonmethodsarereturned.

moduleOther

defthree()end

end

classSingle

defSingle.four()end

end

a=Single.new

defa.one()

end

class<<a

singleton_method(sym)→method

singleton_methods(all=true)→array

Page 567: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

includeOther

deftwo()

end

end

Single.singleton_methods#=>[:four]

a.singleton_methods(false)#=>[:two,:one]

a.singleton_methods#=>[:two,:one,:three]

Marktheobjectastainted.

Objectsthataremarkedastaintedwillberestrictedfromvariousbuilt-inmethods.Thisistopreventinsecuredata,suchascommand-lineargumentsorstringsreadfromKernel#gets,frominadvertentlycompromisingtheuser'ssystem.

Tocheckwhetheranobjectistainted,usetainted?.

Youshouldonlyuntaintataintedobjectifyourcodehasinspecteditanddeterminedthatitissafe.Todosouseuntaint.

In$SAFElevel3,allnewlycreatedobjectsaretaintedandyoucan'tuntaintobjects.

Returnstrueiftheobjectistainted.

Seetaintformoreinformation.

Yieldsselftotheblock,andthenreturnsself.Theprimarypurposeofthismethodisto“tapinto”amethodchain,inordertoperformoperationsonintermediateresultswithinthechain.

taint→obj

tainted?→trueorfalse

tap{|x|...}→obj

Page 568: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(1..10).tap{|x|puts"original:#{x.inspect}"

.to_a.tap{|x|puts"array:#{x.inspect}"

.select{|x|x%2==0}.tap{|x|puts"evens:#{x.inspect}"

.map{|x|x*x}.tap{|x|puts"squares:#{x.inspect}"

CreatesanewEnumeratorwhichwillenumeratebycallingmethodonobj,passingargsifany.

Ifablockisgiven,itwillbeusedtocalculatethesizeoftheenumeratorwithouttheneedtoiterateit(seeEnumerator#size).

Examplesstr="xyz"

enum=str.enum_for(:each_byte)

enum.each{|b|putsb}

#=>120

#=>121

#=>122

#protectanarrayfrombeingmodifiedbysome_method

a=[1,2,3]

some_method(a.to_enum)

Itistypicaltocall#to_enumwhendefiningmethodsforagenericEnumerable,incasenoblockispassed.

Hereissuchanexample,withparameterpassingandasizingblock:

to_enum(method=:each,*args)→enumenum_for(method=:each,*args)→enumto_enum(method=:each,*args){|*args|block}→enumenum_for(method=:each,*args){|*args|block}→enum

Page 569: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleEnumerable

#agenericmethodtorepeatthevaluesofanyenumerable

defrepeat(n)

raiseArgumentError,"#{n}isnegative!"ifn<0

unlessblock_given?

returnto_enum(__method__,n)do#__method__is:repeathere

sz=size#Callsizeandmultiplybyn...

sz*nifsz#butreturnnilifsizeitselfisnil

end

end

eachdo|*val|

n.times{yield*val}

end

end

end

%[helloworld].repeat(2){|w|putsw}

#=>Prints'hello','hello','world','world'

enum=(1..14).repeat(3)

#=>returnsanEnumeratorwhencalledwithoutablock

enum.first(4)#=>[1,1,1,2]

enum.size#=>42

Returnsastringrepresentingobj.Thedefaultto_sprintstheobject'sclassandanencodingoftheobjectid.Asaspecialcase,thetop-levelobjectthatistheinitialexecutioncontextofRubyprogramsreturns“main''.

Deprecatedmethodthatisequivalenttountaint.

Removesthetaintedmarkfromtheobject.

Seetaintformoreinformation.

to_s→string

trust→obj

untaint→obj

Page 570: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Deprecatedmethodthatisequivalenttotaint.

Deprecatedmethodthatisequivalenttotainted?.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

untrust→obj

untrusted?→trueorfalse

Page 571: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleObjectSpaceTheObjectSpacemodulecontainsanumberofroutinesthatinteractwiththegarbagecollectionfacilityandallowyoutotraversealllivingobjectswithaniterator.

ObjectSpacealsoprovidessupportforobjectfinalizers,procsthatwillbecalledwhenaspecificobjectisabouttobedestroyedbygarbagecollection.

a="A"

b="B"

ObjectSpace.define_finalizer(a,proc{|id|puts"Finalizeroneon#{id}"

ObjectSpace.define_finalizer(b,proc{|id|puts"Finalizertwoon#{id}"

produces:

Finalizertwoon537763470

Finalizeroneon537763480

InFilesgc.c

PublicClassMethods

Page 572: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Convertsanobjectidtoareferencetotheobject.Maynotbecalledonanobjectidpassedasaparametertoafinalizer.

s="Iamastring"#=>"Iamastring"

r=ObjectSpace._id2ref(s.object_id)#=>"Iamastring"

r==s#=>true

Countsobjectsforeachtype.

Itreturnsahash,suchas:

{

:TOTAL=>10000,

:FREE=>3011,

:T_OBJECT=>6,

:T_CLASS=>404,

#...

}

Thecontentsofthereturnedhashareimplementationspecific.Itmaybechangedinfuture.

Iftheoptionalargumentresult_hashisgiven,itisoverwrittenandreturned.Thisisintendedtoavoidprobeeffect.

ThismethodisonlyexpectedtoworkonCRuby.

AddsaProcasafinalizer,tobecalledafterobjwasdestroyed.

_id2ref(object_id)→an_object

count_objects([result_hash])→hash

define_finalizer(obj,aProc=proc())

each_object([module]){|obj|...}→fixnumeach_object([module])→an_enumerator

Page 573: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Callstheblockonceforeachliving,nonimmediateobjectinthisRubyprocess.Ifmoduleisspecified,callstheblockforonlythoseclassesormodulesthatmatch(orareasubclassof)module.Returnsthenumberofobjectsfound.Immediateobjects(Fixnums,Symbolstrue,false,andnil)areneverreturned.Intheexamplebelow,each_objectreturnsboththenumberswedefinedandseveralconstantsdefinedintheMathmodule.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

a=102.7

b=95#Won'tbereturned

c=12345678987654321

count=ObjectSpace.each_object(Numeric){|x|px}

puts"Totalcount:#{count}"

produces:

12345678987654321

102.7

2.71828182845905

3.14159265358979

2.22044604925031e-16

1.7976931348623157e+308

2.2250738585072e-308

Totalcount:7

Initiatesgarbagecollection,unlessmanuallydisabled.

start→nilgarbage_collect→nilstart(full_mark:true,immediate_sweep:true)→nilgarbage_collect(full_mark:true,immediate_sweep:true)→nil

Page 574: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thismethodisdefinedwithkeywordargumentsthatdefaulttotrue:

defGC.start(full_mark:true,immediate_sweep:true);

Usefull_mark:falsetoperformaminorGC.Useimmediate_sweep:falsetodefersweeping(uselazysweep).

Note:Thesekeywordargumentsareimplementationandversiondependent.Theyarenotguaranteedtobefuture-compatible,andmaybeignorediftheunderlyingimplementationdoesnotsupportthem.

Removesallfinalizersforobj.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

undefine_finalizer(obj)

Page 575: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classObjectSpace::WeakMapAnObjectSpace::WeakMapobjectholdsreferencestoanyobjects,butthoseobjectscangetgarbagecollected.

ThisclassismostlyusedinternallybyWeakRef,pleaseuselib/weakref.rbforthepublicinterface.

InFilesgc.c

ParentObject

IncludedModulesEnumerable

PublicInstanceMethods

Retrievesaweaklyreferencedobjectwiththegivenkey

[](p1)

Page 576: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Createsaweakreferencefromthegivenkeytothegivenvalue

Iteratesoverkeysandobjectsinaweaklyreferencedobject

Iteratesoverkeysandobjectsinaweaklyreferencedobject

Iteratesoverkeysandobjectsinaweaklyreferencedobject

Iteratesoverkeysandobjectsinaweaklyreferencedobject

Returnstrueifkeyisregistered

Returnstrueifkeyisregistered

Iteratesoverkeysandobjectsinaweaklyreferenced

[]=(p1,p2)

each()

each_key()

each_pair()

each_value()

include?(p1)

inspect()

key?(p1)

keys()

Page 577: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

object

Returnstrueifkeyisregistered

Iteratesovervaluesandobjectsinaweaklyreferencedobject

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

length()

member?(p1)

size()

values()

Page 578: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classProcProcobjectsareblocksofcodethathavebeenboundtoasetoflocalvariables.Oncebound,thecodemaybecalledindifferentcontextsandstillaccessthosevariables.

defgen_times(factor)

returnProc.new{|n|n*factor}

end

times3=gen_times(3)

times5=gen_times(5)

times3.call(12)#=>36

times5.call(5)#=>25

times3.call(times5.call(4))#=>60

InFilesproc.c

ParentObject

PublicClassMethods

CreatesanewProcobject,boundtothecurrent

new{|...|block}→a_procnew→a_proc

Page 579: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

context.Proc::newmaybecalledwithoutablockonlywithinamethodwithanattachedblock,inwhichcasethatblockisconvertedtotheProcobject.

defproc_from

Proc.new

end

proc=proc_from{"hello"}

proc.call#=>"hello"

PublicInstanceMethods

Invokestheblockwithobjastheproc'sparameterlike#call.Itistoallowaprocobjecttobeatargetofwhenclauseinacasestatement.

Invokestheblock,settingtheblock'sparameterstothevaluesinparamsusingsomethingclosetomethodcallingsemantics.Generatesawarningifmultiplevaluesarepassedtoaprocthatexpectsjustone(previouslythissilentlyconvertedtheparameterstoanarray).Notethatprc.()invokesprc.call()withtheparametersgiven.It'sasyntaxsugartohide“call”.

Forprocscreatedusinglambdaor->()anerrorisgeneratedifthewrongnumberofparametersarepassedtoaProcwithmultipleparameters.ForprocscreatedusingProc.neworKernel.proc,extraparametersaresilentlydiscarded.

proc===obj→result_of_proc

call(params,...)→objprc[params,...]→obj(params,...)→obj

Page 580: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthevalueofthelastexpressionevaluatedintheblock.SeealsoProc#yield.

a_proc=Proc.new{|a,*b|b.collect{|i|i*a}}

a_proc.call(9,1,2,3)#=>[9,18,27]

a_proc[9,1,2,3]#=>[9,18,27]

a_proc=lambda{|a,b|a}

a_proc.call(1,2,3)

produces:

prog.rb:4:in`blockin<main>':wrongnumberofarguments(3for2)(ArgumentError)

fromprog.rb:5:in`call'

fromprog.rb:5:in`<main>'

Returnsthenumberofmandatoryarguments.Iftheblockisdeclaredtotakenoarguments,returns0.Iftheblockisknowntotakeexactlynarguments,returnsn.Iftheblockhasoptionalarguments,returns-n-1,wherenisthenumberofmandatoryarguments,withtheexceptionforblocksthatarenotlambdasandhaveonlyafinitenumberofoptionalarguments;inthislattercase,returnsn.Keywordsargumentswillconsideredasasingleadditionalargument,thatargumentbeingmandatoryifanykeywordargumentismandatory.Aprocwithnoargumentdeclarationsisthesameasablockdeclaring||asitsarguments.

proc{}.arity#=>0

proc{||}.arity#=>0

proc{|a|}.arity#=>1

proc{|a,b|}.arity#=>2

proc{|a,b,c|}.arity#=>3

proc{|*a|}.arity#=>-1

proc{|a,*b|}.arity#=>-2

proc{|a,*b,c|}.arity#=>-3

proc{|x:,y:,z:0|}.arity#=>1

proc{|*a,x:,y:0|}.arity#=>-2

arity→fixnum

Page 581: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

proc{|x=0|}.arity#=>0

lambda{|x=0|}.arity#=>-1

proc{|x=0,y|}.arity#=>1

lambda{|x=0,y|}.arity#=>-2

proc{|x=0,y=0|}.arity#=>0

lambda{|x=0,y=0|}.arity#=>-1

proc{|x,y=0|}.arity#=>1

lambda{|x,y=0|}.arity#=>-2

proc{|(x,y),z=0|}.arity#=>1

lambda{|(x,y),z=0|}.arity#=>-2

proc{|a,x:0,y:0|}.arity#=>1

lambda{|a,x:0,y:0|}.arity#=>-2

Returnsthebindingassociatedwithprc.NotethatKernel#evalacceptseitheraProcoraBindingobjectasitssecondparameter.

deffred(param)

proc{}

end

b=fred(99)

eval("param",b.binding)#=>99

Invokestheblock,settingtheblock'sparameterstothevaluesinparamsusingsomethingclosetomethodcallingsemantics.Generatesawarningifmultiplevaluesarepassedtoaprocthatexpectsjustone(previouslythissilentlyconvertedtheparameterstoanarray).Notethatprc.()invokesprc.call()withtheparametersgiven.It'sasyntaxsugartohide“call”.

Forprocscreatedusinglambdaor->()anerroris

binding→binding

call(params,...)→objprc[params,...]→obj(params,...)→obj

Page 582: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

generatedifthewrongnumberofparametersarepassedtoaProcwithmultipleparameters.ForprocscreatedusingProc.neworKernel.proc,extraparametersaresilentlydiscarded.

Returnsthevalueofthelastexpressionevaluatedintheblock.SeealsoProc#yield.

a_proc=Proc.new{|a,*b|b.collect{|i|i*a}}

a_proc.call(9,1,2,3)#=>[9,18,27]

a_proc[9,1,2,3]#=>[9,18,27]

a_proc=lambda{|a,b|a}

a_proc.call(1,2,3)

produces:

prog.rb:4:in`blockin<main>':wrongnumberofarguments(3for2)(ArgumentError)

fromprog.rb:5:in`call'

fromprog.rb:5:in`<main>'

Returnsacurriedproc.Iftheoptionalarityargumentisgiven,itdeterminesthenumberofarguments.Acurriedprocreceivessomearguments.Ifasufficientnumberofargumentsaresupplied,itpassesthesuppliedargumentstotheoriginalprocandreturnstheresult.Otherwise,returnsanothercurriedprocthattakestherestofarguments.

b=proc{|x,y,z|(x||0)+(y||0)+(z||0)}

pb.curry[1][2][3]#=>6

pb.curry[1,2][3,4]#=>6

pb.curry(5)[1][2][3][4][5]#=>6

pb.curry(5)[1,2][3,4][5]#=>6

pb.curry(1)[1]#=>1

b=proc{|x,y,z,*w|(x||0)+(y||0)+(z||0)+w.inject

pb.curry[1][2][3]#=>6

curry→a_proccurry(arity)→a_proc

Page 583: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

pb.curry[1,2][3,4]#=>10

pb.curry(5)[1][2][3][4][5]#=>15

pb.curry(5)[1,2][3,4][5]#=>15

pb.curry(1)[1]#=>1

b=lambda{|x,y,z|(x||0)+(y||0)+(z||0)}

pb.curry[1][2][3]#=>6

pb.curry[1,2][3,4]#=>wrongnumberofarguments(4for3)

pb.curry(5)#=>wrongnumberofarguments(5for3)

pb.curry(1)#=>wrongnumberofarguments(1for3)

b=lambda{|x,y,z,*w|(x||0)+(y||0)+(z||0)+w

pb.curry[1][2][3]#=>6

pb.curry[1,2][3,4]#=>10

pb.curry(5)[1][2][3][4][5]#=>15

pb.curry(5)[1,2][3,4][5]#=>15

pb.curry(1)#=>wrongnumberofarguments(1for3)

b=proc{:foo}

pb.curry[]#=>:foo

Returnsahashvaluecorrespondingtoprocbody.

SeealsoObject#hash.

Aliasfor:to_s

ReturnstrueforaProcobjectforwhichargumenthandlingisrigid.Suchprocsaretypicallygeneratedbylambda.

AProcobjectgeneratedbyprocignoresextraarguments.

proc{|a,b|[a,b]}.call(1,2,3)#=>[1,2]

hash→integer

inspect()

lambda?→trueorfalse

Page 584: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Itprovidesnilformissingarguments.

proc{|a,b|[a,b]}.call(1)#=>[1,nil]

Itexpandsasinglearrayargument.

proc{|a,b|[a,b]}.call([1,2])#=>[1,2]

AProcobjectgeneratedbylambdadoesn'thavesuchtricks.

lambda{|a,b|[a,b]}.call(1,2,3)#=>ArgumentError

lambda{|a,b|[a,b]}.call(1)#=>ArgumentError

lambda{|a,b|[a,b]}.call([1,2])#=>ArgumentError

#lambda?isapredicateforthetricks.Itreturnstrueifnotricksapply.

lambda{}.lambda?#=>true

proc{}.lambda?#=>false

::newisthesameasproc.

Proc.new{}.lambda?#=>false

lambda,procand::newpreservethetricksofaProcobjectgivenby&argument.

lambda(&lambda{}).lambda?#=>true

proc(&lambda{}).lambda?#=>true

Proc.new(&lambda{}).lambda?#=>true

lambda(&proc{}).lambda?#=>false

proc(&proc{}).lambda?#=>false

Proc.new(&proc{}).lambda?#=>false

AProcobjectgeneratedby&argumenthasthetricks

defn(&b)b.lambda?end

n{}#=>false

The&argumentpreservesthetricksifaProcobject

Page 585: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

isgivenby&argument.

n(&lambda{})#=>true

n(&proc{})#=>false

n(&Proc.new{})#=>false

AProcobjectconvertedfromamethodhasnotricks.

defm()end

method(:m).to_proc.lambda?#=>true

n(&method(:m))#=>true

n(&method(:m).to_proc)#=>true

define_methodistreatedthesameasmethoddefinition.Thedefinedmethodhasnotricks.

classC

define_method(:d){}

end

C.new.d(1,2)#=>ArgumentError

C.new.method(:d).to_proc.lambda?#=>true

define_methodalwaysdefinesamethodwithoutthetricks,evenifanon-lambdaProcobjectisgiven.Thisistheonlyexceptionforwhichthetricksarenotpreserved.

classC

define_method(:e,&proc{})

end

C.new.e(1,2)#=>ArgumentError

C.new.method(:e).to_proc.lambda?#=>true

Thisexceptioninsuresthatmethodsneverhavetricksandmakesiteasytohavewrapperstodefinemethodsthatbehaveasusual.

classC

defself.def2(name,&body)

define_method(name,&body)

end

def2(:f){}

Page 586: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

C.new.f(1,2)#=>ArgumentError

Thewrapperdef2definesamethodwhichhasnotricks.

Returnstheparameterinformationofthisproc.

prc=lambda{|x,y=42,*other|}

prc.parameters#=>[[:req,:x],[:opt,:y],[:rest,:other]]

ReturnstheRubysourcefilenameandlinenumbercontainingthisprocornilifthisprocwasnotdefinedinRuby(i.e.native)

PartoftheprotocolforconvertingobjectstoProcobjects.InstancesofclassProcsimplyreturnthemselves.

Returnstheuniqueidentifierforthisproc,alongwithanindicationofwheretheprocwasdefined.

Alsoaliasedas:inspect

Invokestheblock,settingtheblock'sparameterstothevaluesinparamsusingsomethingcloseto

parameters→array

source_location→[String,Fixnum]

to_proc→proc

to_s→string

call(params,...)→objprc[params,...]→obj(params,...)→obj

Page 587: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

methodcallingsemantics.Generatesawarningifmultiplevaluesarepassedtoaprocthatexpectsjustone(previouslythissilentlyconvertedtheparameterstoanarray).Notethatprc.()invokesprc.call()withtheparametersgiven.It'sasyntaxsugartohide“call”.

Forprocscreatedusinglambdaor->()anerrorisgeneratedifthewrongnumberofparametersarepassedtoaProcwithmultipleparameters.ForprocscreatedusingProc.neworKernel.proc,extraparametersaresilentlydiscarded.

Returnsthevalueofthelastexpressionevaluatedintheblock.SeealsoProc#yield.

a_proc=Proc.new{|a,*b|b.collect{|i|i*a}}

a_proc.call(9,1,2,3)#=>[9,18,27]

a_proc[9,1,2,3]#=>[9,18,27]

a_proc=lambda{|a,b|a}

a_proc.call(1,2,3)

produces:

prog.rb:4:in`blockin<main>':wrongnumberofarguments(3for2)(ArgumentError)

fromprog.rb:5:in`call'

fromprog.rb:5:in`<main>'

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 588: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleProcess

InFilesprocess.cruby.c

Constants

CLOCK_BOOTTIME

CLOCK_BOOTTIME_ALARM

CLOCK_MONOTONIC

CLOCK_MONOTONIC_COARSE

CLOCK_MONOTONIC_FAST

CLOCK_MONOTONIC_PRECISE

CLOCK_MONOTONIC_RAW

CLOCK_PROCESS_CPUTIME_ID

CLOCK_PROF

CLOCK_REALTIME

CLOCK_REALTIME_ALARM

CLOCK_REALTIME_COARSE

Page 589: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CLOCK_REALTIME_FAST

CLOCK_REALTIME_PRECISE

CLOCK_SECOND

CLOCK_THREAD_CPUTIME_ID

CLOCK_UPTIME

CLOCK_UPTIME_FAST

CLOCK_UPTIME_PRECISE

CLOCK_VIRTUAL

PRIO_PGRP

see::setpriority

PRIO_PROCESS

see::setpriority

PRIO_USER

see::setpriority

RLIMIT_AS

Maximumsizeoftheprocess'svirtualmemory(addressspace)inbytes.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_CORE

Maximumsizeofthecorefile.

seethesystemgetrlimit(2)manualfordetails.

Page 590: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

RLIMIT_CPU

CPUtimelimitinseconds.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_DATA

Maximumsizeoftheprocess'sdatasegment.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_FSIZE

Maximumsizeoffilesthattheprocessmaycreate.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_MEMLOCK

MaximumnumberofbytesofmemorythatmaybelockedintoRAM.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_MSGQUEUE

SpecifiesthelimitonthenumberofbytesthatcanbeallocatedforPOSIXmessagequeuesfortherealuserIDofthecallingprocess.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_NICE

Specifiesaceilingtowhichtheprocess'snicevaluecanberaised.

seethesystemgetrlimit(2)manualfordetails.

Page 591: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

RLIMIT_NOFILE

Specifiesavalueonegreaterthanthemaximumfiledescriptornumberthatcanbeopenedbythisprocess.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_NPROC

ThemaximumnumberofprocessesthatcanbecreatedfortherealuserIDofthecallingprocess.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_RSS

Specifiesthelimit(inpages)oftheprocess'sresidentset.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_RTPRIO

Specifiesaceilingonthereal-timeprioritythatmaybesetforthisprocess.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_RTTIME

SpecifieslimitonCPUtimethisprocessscheduledunderareal-timeschedulingpolicycanconsume.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_SBSIZE

Maximumsizeofthesocketbuffer.

RLIMIT_SIGPENDING

Page 592: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SpecifiesalimitonthenumberofsignalsthatmaybequeuedfortherealuserIDofthecallingprocess.

seethesystemgetrlimit(2)manualfordetails.

RLIMIT_STACK

Maximumsizeofthestack,inbytes.

seethesystemgetrlimit(2)manualfordetails.

RLIM_INFINITY

see::setrlimit

RLIM_SAVED_CUR

see::setrlimit

RLIM_SAVED_MAX

see::setrlimit

WNOHANG

see::wait

WUNTRACED

see::wait

PublicClassMethods

Terminateexecutionimmediately,effectivelyby

abortKernel::abort([msg])Process::abort([msg])

Page 593: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

callingKernel.exit(false).Ifmsgisgiven,itiswrittentoSTDERRpriortoterminating.

Returnsthenameofthescriptbeingexecuted.Thevalueisnotaffectedbyassigninganewvalueto$0.

ThismethodfirstappearedinRuby2.1toserveasaglobalvariablefreemeanstogetthescriptname.

ReturnsthetimeresolutionreturnedbyPOSIX::clock_getres()function.

clock_idspecifiesakindofclock.SeethedocumentofProcess.clock_gettimefordetails.

clock_idcanbeasymbolasProcess.clock_gettime.Howevertheresultmaynotbeaccurate.Forexample,+::clock_getres(:GETTIMEOFDAY_BASED_CLOCK_REALTIME)+returns1.0e-06whichmeans1microsecond,butactualresolutioncanbemorecoarse.

Ifthegivenclock_idisnotsupported,Errno::EINVALisraised.

unitspecifiesatypeofthereturnvalue.Process.clock_getresacceptsunitasProcess.clock_gettime.Thedefaultvalue,:float_second,isalsosameasProcess.clock_gettime.

Process.clock_getresalsoaccepts:hertzasunit.:hertzmeansathereciprocalof:float_second.

:hertzcanbeusedtoobtaintheexactvalueoftheclocktickspersecondfortimes()functionand

argv0→frozen_string

clock_getres(clock_id[,unit])→number

Page 594: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CLOCKS_PER_SECforclock()function.

+::clock_getres(:TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID,:hertz)+returnstheclocktickspersecond.

+::clock_getres(:CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID,:hertz)+returnsCLOCKS_PER_SEC.

pProcess.clock_getres(Process::CLOCK_MONOTONIC)

#=>1.0e-09

ReturnsatimereturnedbyPOSIX::clock_gettime()function.

pProcess.clock_gettime(Process::CLOCK_MONOTONIC)

#=>896053.968060096

clock_idspecifiesakindofclock.ItisspecifedasaconstantwhichbeginswithProcess::CLOCK_suchasProcess::CLOCK_REALTIMEandProcess::CLOCK_MONOTONIC.

ThesupportedconstantsdependsonOSandversion.Rubyprovidesfollowingtypesofclock_idifavailable.

CLOCK_REALTIMESUSv2to4,Linux2.5.63,FreeBSD3.0,NetBSD2.0,OpenBSD2.1

CLOCK_MONOTONICSUSv3to4,Linux2.5.63,FreeBSD3.0,NetBSD2.0,OpenBSD3.4

CLOCK_PROCESS_CPUTIME_IDSUSv3to4,Linux2.5.63,OpenBSD5.4

clock_gettime(clock_id[,unit])→number

Page 595: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CLOCK_THREAD_CPUTIME_IDSUSv3to4,Linux2.5.63,FreeBSD7.1,OpenBSD5.4

CLOCK_VIRTUALFreeBSD3.0,OpenBSD2.1

CLOCK_PROFFreeBSD3.0,OpenBSD2.1

CLOCK_REALTIME_FASTFreeBSD8.1

CLOCK_REALTIME_PRECISEFreeBSD8.1

CLOCK_REALTIME_COARSELinux2.6.32

CLOCK_REALTIME_ALARMLinux3.0

CLOCK_MONOTONIC_FASTFreeBSD8.1

CLOCK_MONOTONIC_PRECISEFreeBSD8.1

CLOCK_MONOTONIC_COARSELinux2.6.32

CLOCK_MONOTONIC_RAWLinux2.6.28

Page 596: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CLOCK_BOOTTIMELinux2.6.39

CLOCK_BOOTTIME_ALARMLinux3.0

CLOCK_UPTIMEFreeBSD7.0,OpenBSD5.5

CLOCK_UPTIME_FASTFreeBSD8.1

CLOCK_UPTIME_PRECISEFreeBSD8.1

CLOCK_SECONDFreeBSD8.1

NotethatSUSstandsforSingleUnixSpecification.SUScontainsPOSIXand::clock_gettimeisdefinedinthePOSIXpart.SUSdefinesCLOCK_REALTIMEmandatorybutCLOCK_MONOTONIC,CLOCK_PROCESS_CPUTIME_IDandCLOCK_THREAD_CPUTIME_IDareoptional.

Also,severalsymbolsareacceptedasclock_id.Thereareemulationsfor::clock_gettime().

Forexample,Process::CLOCK_REALTIMEisdefinedas:GETTIMEOFDAY_BASED_CLOCK_REALTIMEwhen::clock_gettime()isnotavailable.

EmulationsforCLOCK_REALTIME:

:GETTIMEOFDAY_BASED_CLOCK_REALTIMEUsegettimeofday()definedbySUS.(SUSv4obsoletedit,though.)The

Page 597: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

resolutionis1microsecond.

:TIME_BASED_CLOCK_REALTIMEUsetime()definedbyISOC.Theresolutionis1second.

EmulationsforCLOCK_MONOTONIC:

:MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONICUsemach_absolute_time(),availableonDarwin.TheresolutionisCPUdependent.

:TIMES_BASED_CLOCK_MONOTONICUsetheresultvalueoftimes()definedbyPOSIX.POSIXdefinesitas“times()shallreturntheelapsedrealtime,inclockticks,sinceanarbitrarypointinthepast(forexample,systemstart-uptime)”.Forexample,GNU/Linuxreturnsavaluebasedonjiffiesanditismonotonic.However,4.4BSDusesgettimeofday()anditisnotmonotonic.(FreeBSDuses::clock_gettime(CLOCK_MONOTONIC)instead,though.)Theresolutionistheclocktick.“getconfCLK_TCK”commandshowstheclocktickspersecond.(TheclocktickspersecondisdefinedbyHZmacroinoldersystems.)Ifitis100andclock_tis32bitsintegertype,theresolutionis10millisecondandcannotrepresentover497days.

EmulationsforCLOCK_PROCESS_CPUTIME_ID:

:GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_IDUsegetrusage()definedbySUS.getrusage()isusedwithRUSAGE_SELFtoobtainthetimeonlyforthecallingprocess

Page 598: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(excludingthetimeforchildprocesses).Theresultisadditionofusertime(ru_utime)andsystemtime(ru_stime).Theresolutionis1microsecond.

:TIMES_BASED_CLOCK_PROCESS_CPUTIME_IDUsetimes()definedbyPOSIX.Theresultisadditionofusertime(tms_utime)andsystemtime(tms_stime).tms_cutimeandtms_cstimeareignoredtoexcludethetimeforchildprocesses.Theresolutionistheclocktick.“getconfCLK_TCK”commandshowstheclocktickspersecond.(TheclocktickspersecondisdefinedbyHZmacroinoldersystems.)Ifitis100,theresolutionis10millisecond.

:CLOCK_BASED_CLOCK_PROCESS_CPUTIME_IDUseclock()definedbyISOC.Theresolutionis1/CLOCKS_PER_SEC.CLOCKS_PER_SECistheC-levelmacrodefinedbytime.h.SUSdefinesCLOCKS_PER_SECis1000000.Non-Unixsystemsmaydefineitadifferentvalue,though.IfCLOCKS_PER_SECis1000000asSUS,theresolutionis1microsecond.IfCLOCKS_PER_SECis1000000andclock_tis32bitsintegertype,itcannotrepresentover72minutes.

Ifthegivenclock_idisnotsupported,Errno::EINVALisraised.

unitspecifiesatypeofthereturnvalue.

:float_secondnumberofsecondsasafloat(default)

Page 599: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

:float_millisecondnumberofmillisecondsasafloat

:float_microsecondnumberofmicrosecondsasafloat

:secondnumberofsecondsasaninteger

:millisecondnumberofmillisecondsasaninteger

:microsecondnumberofmicrosecondsasaninteger

:nanosecondnumberofnanosecondsasaninteger

Theunderlyingfunction,::clock_gettime(),returnsanumberofnanoseconds.Floatobject(IEEE754double)isnotenoughtorepresentthereturnvalueforCLOCK_REALTIME.Iftheexactnanosecondsvalueisrequired,use:nanosecondsastheunit.

Theorigin(zero)ofthereturnedvaluevaries.Forexample,systemstartuptime,processstartuptime,theEpoch,etc.

TheorigininCLOCK_REALTIMEisdefinedastheEpoch(1970-01-0100:00:00UTC).Butsomesystemscountleapsecondsandothersdoesn't.Sotheresultcanbeinterpreteddifferentlyacrosssystems.Time.nowisrecommendedoverCLOCK_REALTIME.

Page 600: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Detachtheprocessfromcontrollingterminalandruninthebackgroundassystemdaemon.Unlesstheargumentnochdiristrue(i.e.nonfalse),itchangesthecurrentworkingdirectorytotheroot(“/”).Unlesstheargumentnocloseistrue,daemon()willredirectstandardinput,standardoutputandstandarderrorto/dev/null.Returnzeroonsuccess,orraiseoneofErrno::*.

Someoperatingsystemsretainthestatusofterminatedchildprocessesuntiltheparentcollectsthatstatus(normallyusingsomevariantofwait().Iftheparentnevercollectsthisstatus,thechildstaysaroundasazombieprocess.Process::detachpreventsthisbysettingupaseparateRubythreadwhosesolejobistoreapthestatusoftheprocesspidwhenitterminates.Usedetachonlywhenyoudonotintenttoexplicitlywaitforthechildtoterminate.

Thewaitingthreadreturnstheexitstatusofthedetachedprocesswhenitterminates,soyoucanuseThread#jointoknowtheresult.IfspecifiedpidisnotavalidchildprocessID,thethreadreturnsnilimmediately.

Thewaitingthreadhaspidmethodwhichreturnsthepid.

Inthisfirstexample,wedon'treapthefirstchildprocess,soitappearsasazombieintheprocessstatusdisplay.

p1=fork{sleep0.1}

p2=fork{sleep0.2}

daemon()→0daemon(nochdir=nil,noclose=nil)→0

detach(pid)→thread

Page 601: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Process.waitpid(p2)

sleep2

system("ps-hopid,state-p#{p1}")

produces:

27389Z

Inthenextexample,Process::detachisusedtoreapthechildautomatically.

p1=fork{sleep0.1}

p2=fork{sleep0.2}

Process.detach(p1)

Process.waitpid(p2)

sleep2

system("ps-hopid,state-p#{p1}")

(producesnooutput)

ReturnstheeffectivegroupIDforthisprocess.Notavailableonallplatforms.

Process.egid#=>500

SetstheeffectivegroupIDforthisprocess.Notavailableonallplatforms.

ReturnstheeffectiveuserIDforthisprocess.

egid→fixnumProcess::GID.eid→fixnumProcess::Sys.geteid→fixnum

egid=fixnum→fixnum

euid→fixnumProcess::UID.eid→fixnumProcess::Sys.geteuid→fixnum

Page 602: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Process.euid#=>501

SetstheeffectiveuserIDforthisprocess.Notavailableonallplatforms.

Replacesthecurrentprocessbyrunningthegivenexternalcommand,whichcantakeoneofthefollowingforms:

exec(commandline)

commandlinestringwhichispassedtothestandardshell

exec(cmdname,arg1,...)

commandnameandoneormorearguments(noshell)

exec([cmdname,argv0],arg1,...)

commandname,argvandzeroormorearguments(noshell)

Inthefirstform,thestringistakenasacommandlinethatissubjecttoshellexpansionbeforebeingexecuted.

Thestandardshellalwaysmeans"/bin/sh"onUnix-likesystems,sameasENV["RUBYSHELL"](orENV["COMSPEC"]onWindowsNTseries),andsimilar.

Ifthestringfromthefirstform(exec("command"))followsthesesimplerules:

nometacharacters

noshellreservedwordandnospecialbuilt-in

euid=user

exec([env,]command...[,options])

Page 603: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Rubyinvokesthecommanddirectlywithoutshell

Youcanforceshellinvocationbyadding“;”tothestring(because“;”isametacharacter).

Notethatthisbehaviorisobservablebypidobtained(returnvalueofspawn()andIO#pidforIO.popen)isthepidoftheinvokedcommand,notshell.

Inthesecondform(exec("command1","arg1",...)),thefirstistakenasacommandnameandtherestarepassedasparameterstocommandwithnoshellexpansion.

Inthethirdform(exec(["command","argv0"],"arg1",...)),startingatwo-elementarrayatthebeginningofthecommand,thefirstelementisthecommandtobeexecuted,andthesecondargumentisusedastheargv[0]value,whichmayshowupinprocesslistings.

Inordertoexecutethecommand,oneoftheexec(2)systemcallsareused,sotherunningcommandmayinheritsomeoftheenvironmentoftheoriginalprogram(includingopenfiledescriptors).

Thisbehaviorismodifiedbythegivenenvandoptionsparameters.See::spawnfordetails.

Ifthecommandfailstoexecute(typicallyErrno::ENOENTwhenitwasnotfound)aSystemCallErrorexceptionisraised.

Thismethodmodifiesprocessattributesaccordingtogivenoptionsbeforeexec(2)systemcall.See::spawnformoredetailsaboutthegivenoptions.

Themodifiedattributesmayberetainedwhenexec(2)systemcallfails.

Page 604: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Forexample,hardresourcelimitsarenotrestorable.

Considertocreateachildprocessusing::spawnorKernel#systemifthisisnotacceptable.

exec"echo*"#echoeslistoffilesincurrentdirectory

#nevergethere

exec"echo","*"#echoesanasterisk

#nevergethere

InitiatestheterminationoftheRubyscriptbyraisingtheSystemExitexception.Thisexceptionmaybecaught.Theoptionalparameterisusedtoreturnastatuscodetotheinvokingenvironment.trueandFALSEofstatusmeanssuccessandfailurerespectively.Theinterpretationofotherintegervaluesaresystemdependent.

begin

exit

puts"nevergethere"

rescueSystemExit

puts"rescuedaSystemExitexception"

end

puts"afterbeginblock"

produces:

rescuedaSystemExitexception

afterbeginblock

Justpriortotermination,Rubyexecutesanyat_exitfunctions(seeKernel::at_exit)andrunsanyobjectfinalizers(seeObjectSpace.define_finalizer).

exit(status=true)Kernel::exit(status=true)Process::exit(status=true)

Page 605: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

at_exit{puts"at_exitfunction"}

ObjectSpace.define_finalizer("string",proc{puts"infinalizer"})

exit

produces:

at_exitfunction

infinalizer

Exitstheprocessimmediately.Noexithandlersarerun.statusisreturnedtotheunderlyingsystemastheexitstatus.

Process.exit!(true)

Createsasubprocess.Ifablockisspecified,thatblockisruninthesubprocess,andthesubprocessterminateswithastatusofzero.Otherwise,theforkcallreturnstwice,onceintheparent,returningtheprocessIDofthechild,andonceinthechild,returningnil.ThechildprocesscanexitusingKernel.exit!toavoidrunninganyat_exitfunctions.TheparentprocessshoulduseProcess.waittocollecttheterminationstatusesofitschildrenoruseProcess.detachtoregisterdisinterestintheirstatus;otherwise,theoperatingsystemmayaccumulatezombieprocesses.

Thethreadcallingforkistheonlythreadinthecreatedchildprocess.forkdoesn'tcopyotherthreads.

Ifforkisnotusable,Process.respond_to?(:fork)

exit!(status=false)

fork[{block}]→fixnumornilfork[{block}]→fixnumornil

Page 606: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

returnsfalse.

Notethatfork(2)isnotavailableonsomeplatformslikeWindowsandNetBSD4.Thereforeyoushouldusespawn()insteadoffork().

ReturnstheprocessgroupIDforthegivenprocessid.Notavailableonallplatforms.

Process.getpgid(Process.ppid())#=>25527

ReturnstheprocessgroupIDforthisprocess.Notavailableonallplatforms.

Process.getpgid(0)#=>25527

Process.getpgrp#=>25527

Getstheschedulingpriorityforspecifiedprocess,processgroup,oruser.kindindicatesthekindofentitytofind:oneofProcess::PRIO_PGRP,Process::PRIO_USER,orProcess::PRIO_PROCESS.integerisanidindicatingtheparticularprocess,processgroup,oruser(anidof0meanscurrent).Lowerprioritiesaremorefavorableforscheduling.Notavailableonallplatforms.

Process.getpriority(Process::PRIO_USER,0)#=>19

Process.getpriority(Process::PRIO_PROCESS,0)#=>19

Getstheresourcelimitoftheprocess.cur_limit

getpgid(pid)→integer

getpgrp→integer

getpriority(kind,integer)→fixnum

getrlimit(resource)→[cur_limit,max_limit]

Page 607: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

meanscurrent(soft)limitandmax_limitmeansmaximum(hard)limit.

resourceindicatesthekindofresourcetolimit.Itisspecifiedasasymbolsuchas:CORE,astringsuchas"CORE"oraconstantsuchasProcess::RLIMIT_CORE.See::setrlimitfordetails.

cur_limitandmax_limitmaybeProcess::RLIM_INFINITY,Process::RLIM_SAVED_MAXorProcess::RLIM_SAVED_CUR.See::setrlimitandthesystemgetrlimit(2)manualfordetails.

ReturnsthesessionIDforforthegivenprocessid.Ifnotgive,returncurrentprocesssid.Notavailableonallplatforms.

Process.getsid()#=>27422

Process.getsid(0)#=>27422

Process.getsid(Process.pid())#=>27422

Returnsthe(real)groupIDforthisprocess.

Process.gid#=>500

SetsthegroupIDforthisprocess.

getsid()→integergetsid(pid)→integer

gid→fixnumProcess::GID.rid→fixnumProcess::Sys.getgid→fixnum

gid=fixnum→fixnum

groups→array

Page 608: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GetanArrayofthegidsofgroupsinthesupplementalgroupaccesslistforthisprocess.

Process.groups#=>[27,6,10,11]

SetthesupplementalgroupaccesslisttothegivenArrayofgroupIDs.

Process.groups#=>[0,1,2,3,4,6,10,11,20,26,27]

Process.groups=[27,6,10,11]#=>[27,6,10,11]

Process.groups#=>[27,6,10,11]

Initializesthesupplementalgroupaccesslistbyreadingthesystemgroupdatabaseandusingallgroupsofwhichthegivenuserisamember.Thegroupwiththespecifiedgidisalsoaddedtothelist.ReturnstheresultingArrayofthegidsofallthegroupsinthesupplementarygroupaccesslist.Notavailableonallplatforms.

Process.groups#=>[0,1,2,3,4,6,10,11,20,26,27]

Process.initgroups("mgranger",30)#=>[30,6,10,11]

Process.groups#=>[30,6,10,11]

Sendsthegivensignaltothespecifiedprocessid(s)ifpidispositive.IfpidiszerosignalissenttoallprocesseswhosegroupIDisequaltothegroupIDoftheprocess.signalmaybeanintegersignalnumberoraPOSIXsignalname(eitherwithorwithoutaSIGprefix).Ifsignalisnegative(orstartswithaminussign),killsprocessgroupsinsteadofprocesses.Not

groups=array→array

initgroups(username,gid)→array

kill(signal,pid,...)→fixnum

Page 609: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

allsignalsareavailableonallplatforms.ThekeysandvaluesofSignal.listareknownsignalnamesandnumbers,respectively.

pid=forkdo

Signal.trap("HUP"){puts"Ouch!";exit}

#...dosomework...

end

#...

Process.kill("HUP",pid)

Process.wait

produces:

Ouch!

Ifsignalisanintegerbutwrongforsignal,Errno::EINVALorRangeErrorwillberaised.OtherwiseunlesssignalisaStringoraSymbol,andaknownsignalname,ArgumentErrorwillberaised.

Also,Errno::ESRCHorRangeErrorforinvalidpid,Errno::EPERMwhenfailedbecauseofnoprivilege,willberaised.Inthesecases,signalsmayhavebeensenttoprecedingprocesses.

Returnsthemaximumnumberofgidsallowedinthesupplementalgroupaccesslist.

Process.maxgroups#=>32

Setsthemaximumnumberofgidsallowedinthesupplementalgroupaccesslist.

maxgroups→fixnum

maxgroups=fixnum→fixnum

pid→fixnum

Page 610: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstheprocessidofthisprocess.Notavailableonallplatforms.

Process.pid#=>27415

Returnstheprocessidoftheparentofthisprocess.ReturnsuntrustworthyvalueonWin32/64.Notavailableonallplatforms.

puts"Iam#{Process.pid}"

Process.fork{puts"Dadis#{Process.ppid}"}

produces:

Iam27417

Dadis27417

SetstheprocessgroupIDofpid(0indicatesthisprocess)tointeger.Notavailableonallplatforms.

Equivalenttosetpgid(0,0).Notavailableonallplatforms.

SeeProcess#getpriority.

Process.setpriority(Process::PRIO_USER,0,19)#=>0

Process.setpriority(Process::PRIO_PROCESS,0,19)#=>0

Process.getpriority(Process::PRIO_USER,0)#=>19

Process.getpriority(Process::PRIO_PROCESS,0)#=>19

ppid→fixnum

setpgid(pid,integer)→0

setpgrp→0

setpriority(kind,integer,priority)→0

Page 611: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Setstheprocesstitlethatappearsontheps(1)command.Notnecessarilyeffectiveonallplatforms.Noexceptionwillberaisedregardlessoftheresult,norwillNotImplementedErrorberaisedeveniftheplatformdoesnotsupportthefeature.

Callingthismethoddoesnotaffectthevalueof$0.

Process.setproctitle('myapp:worker#%d'%worker_id)

ThismethodfirstappearedinRuby2.1toserveasaglobalvariablefreemeanstochangetheprocesstitle.

Setstheresourcelimitoftheprocess.cur_limitmeanscurrent(soft)limitandmax_limitmeansmaximum(hard)limit.

Ifmax_limitisnotgiven,cur_limitisused.

resourceindicatesthekindofresourcetolimit.Itshouldbeasymbolsuchas:CORE,astringsuchas"CORE"oraconstantsuchasProcess::RLIMIT_CORE.TheavailableresourcesareOSdependent.Rubymaysupportfollowingresources.

AStotalavailablememory(bytes)(SUSv3,NetBSD,FreeBSD,OpenBSDbut4.4BSD-Lite)

COREcoresize(bytes)(SUSv3)

setproctitle(string)→string

setrlimit(resource,cur_limit,max_limit)→nilsetrlimit(resource,cur_limit)→nil

Page 612: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CPUCPUtime(seconds)(SUSv3)

DATAdatasegment(bytes)(SUSv3)

FSIZEfilesize(bytes)(SUSv3)

MEMLOCKtotalsizeformlock(2)(bytes)(4.4BSD,GNU/Linux)

MSGQUEUEallocationforPOSIXmessagequeues(bytes)(GNU/Linux)

NICEceilingonprocess'snice(2)value(number)(GNU/Linux)

NOFILEfiledescriptors(number)(SUSv3)

NPROCnumberofprocessesfortheuser(number)(4.4BSD,GNU/Linux)

RSSresidentmemorysize(bytes)(4.2BSD,GNU/Linux)

RTPRIO

Page 613: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ceilingontheprocess'sreal-timepriority(number)(GNU/Linux)

RTTIMECPUtimeforreal-timeprocess(us)(GNU/Linux)

SBSIZEallsocketbuffers(bytes)(NetBSD,FreeBSD)

SIGPENDINGnumberofqueuedsignalsallowed(signals)(GNU/Linux)

STACKstacksize(bytes)(SUSv3)

cur_limitandmax_limitmaybe:INFINITY,"INFINITY"orProcess::RLIM_INFINITY,whichmeansthattheresourceisnotlimited.TheymaybeProcess::RLIM_SAVED_MAX,Process::RLIM_SAVED_CURandcorrespondingsymbolsandstringstoo.Seesystemsetrlimit(2)manualfordetails.

Thefollowingexampleraisesthesoftlimitofcoresizetothehardlimittotrytomakecoredumppossible.

Process.setrlimit(:CORE,Process.getrlimit(:CORE)[1])

Establishesthisprocessasanewsessionandprocessgroupleader,withnocontrollingtty.Returnsthesessionid.Notavailableonallplatforms.

setsid→fixnum

Page 614: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Process.setsid#=>27422

spawnexecutesspecifiedcommandandreturnitspid.

pid=spawn("tarxfruby-2.0.0-p195.tar.bz2")

Process.waitpid

pid=spawn(RbConfig.ruby,"-eputs'Hello,world!'")

Process.waitpid

ThismethodissimilartoKernel#systembutitdoesn'twaitforthecommandtofinish.

TheparentprocessshoulduseProcess.waittocollecttheterminationstatusofitschildoruseProcess.detachtoregisterdisinterestintheirstatus;otherwise,theoperatingsystemmayaccumulatezombieprocesses.

spawnhasbunchofoptionstospecifyprocessattributes:

env:hash

name=>val:settheenvironmentvariable

name=>nil:unsettheenvironmentvariable

command...:

commandline:commandlinestringwhich

cmdname,arg1,...:commandnameandoneor

[cmdname,argv0],arg1,...:commandname,argv[0]

options:hash

clearingenvironmentvariables:

:unsetenv_others=>true:clearenvironmentvariables

:unsetenv_others=>false:don'tclear(default)

processgroup:

:pgroup=>trueor0:makeanewprocessgroup

:pgroup=>pgid:jointospecifiedprocessgroup

:pgroup=>nil:don'tchangetheprocessgroup

spawn([env,]command...[,options])→pidspawn([env,]command...[,options])→pid

Page 615: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

createnewprocessgroup:Windowsonly

:new_pgroup=>true:thenewprocessistheroot

:new_pgroup=>false:don'tcreateanewprocessgroup(default)

resourcelimit:resourcenameiscore,cpu,data,etc.SeeProcess.setrlimit.

:rlimit_resourcename=>limit

:rlimit_resourcename=>[cur_limit,max_limit]

umask:

:umask=>int

redirection:

key:

FD:singlefiledescriptorinchildprocess

[FD,FD,...]:multiplefiledescriptorinchildprocess

value:

FD:redirecttothefiledescriptorinparentprocess

string:redirecttofilewithopen(string,"r"or"w")

[string]:redirecttofilewithopen(string,File::RDONLY)

[string,open_mode]:redirecttofilewithopen(string,open_mode,0644)

[string,open_mode,perm]:redirecttofilewithopen(string,open_mode,perm)

[:child,FD]:redirecttotheredirectedfiledescriptor

:close:closethefiledescriptorinchildprocess

FDisoneoffollows

:in:thefiledescriptor0whichisthestandardinput

:out:thefiledescriptor1whichisthestandardoutput

:err:thefiledescriptor2whichisthestandarderror

integer:thefiledescriptorofspecifiedtheinteger

io:thefiledescriptorspecifiedasio.fileno

filedescriptorinheritance:closenon-redirectednon-standardfds(3,4,5,...)ornot

:close_others=>true:don'tinherit

currentdirectory:

:chdir=>str

The'cmdname,arg1,...'formdoesnotusetheshell

ondifferentOSes,differentthingsareprovidedas

commands.Anexampleofthisis'echo',whichisabuilt

onWindows,butisanormalprogramonLinuxandMac

Thismeansthat%xProcess.spawn'echo','%Path%'`will

thecontentsofthe%x%Path%`environmentvariableon

but%xProcess.spawn'echo','$PATH'`printstheliteral

Ifahashisgivenasenv,theenvironmentisupdatedbyenvbeforeexec(2)inthechildprocess.Ifapairinenvhasnilasthevalue,thevariableisdeleted.

#setFOOasBARandunsetBAZ.

pid=spawn({"FOO"=>"BAR","BAZ"=>nil},command)

Page 616: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ifahashisgivenasoptions,itspecifiesprocessgroup,createnewprocessgroup,resourcelimit,currentdirectory,umaskandredirectsforthechildprocess.Also,itcanbespecifiedtoclearenvironmentvariables.

The:unsetenv_otherskeyinoptionsspecifiestoclearenvironmentvariables,otherthanspecifiedbyenv.

pid=spawn(command,:unsetenv_others=>true)#noenvironmentvariable

pid=spawn({"FOO"=>"BAR"},command,:unsetenv_others=

The:pgroupkeyinoptionsspecifiesaprocessgroup.Thecorrespondingvalueshouldbetrue,zeroorpositiveinteger.trueandzeromeanstheprocessshouldbeaprocessleaderofanewprocessgroup.Othervaluesspecifiesaprocessgrouptobebelongs.

pid=spawn(command,:pgroup=>true)#processleader

pid=spawn(command,:pgroup=>10)#belongstotheprocessgroup10

The:new_pgroupkeyinoptionsspecifiestopassCREATE_NEW_PROCESS_GROUPflagtoCreateProcessW()thatisWindowsAPI.ThisoptionisonlyforWindows.truemeansthenewprocessistherootprocessofthenewprocessgroup.ThenewprocesshasCTRL+Cdisabled.ThisflagisnecessaryforProcess.kill(:SIGINT,pid)onthesubprocess.:new_pgroupisfalsebydefault.

pid=spawn(command,:new_pgroup=>true)#newprocessgroup

pid=spawn(command,:new_pgroup=>false)#sameprocessgroup

The:rlimit_fookeyspecifiesaresourcelimit.foo

Page 617: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

shouldbeoneofresourcetypessuchascore.Thecorrespondingvalueshouldbeanintegeroranarraywhichhaveoneortwointegers:sameascur_limitandmax_limitargumentsfor::setrlimit.

cur,max=Process.getrlimit(:CORE)

pid=spawn(command,:rlimit_core=>[0,max])#disablecoretemporary.

pid=spawn(command,:rlimit_core=>max)#enablecoredump

pid=spawn(command,:rlimit_core=>0)#neverdumpcore.

The:umaskkeyinoptionsspecifiestheumask.

pid=spawn(command,:umask=>077)

The:in,:out,:err,afixnum,anIOandanarraykeyspecifiesaredirection.Theredirectionmapsafiledescriptorinthechildprocess.

Forexample,stderrcanbemergedintostdoutasfollows:

pid=spawn(command,:err=>:out)

pid=spawn(command,2=>1)

pid=spawn(command,STDERR=>:out)

pid=spawn(command,STDERR=>STDOUT)

Thehashkeysspecifiesafiledescriptorinthechildprocessstartedbyspawn.:err,2andSTDERRspecifiesthestandarderrorstream(stderr).

Thehashvaluesspecifiesafiledescriptorintheparentprocesswhichinvokesspawn.:out,1andSTDOUTspecifiesthestandardoutputstream(stdout).

Intheaboveexample,thestandardoutputinthechildprocessisnotspecified.Soitisinheritedfromtheparentprocess.

Thestandardinputstream(stdin)canbespecifiedby:in,0andSTDIN.

Page 618: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Afilenamecanbespecifiedasahashvalue.

pid=spawn(command,:in=>"/dev/null")#readmode

pid=spawn(command,:out=>"/dev/null")#writemode

pid=spawn(command,:err=>"log")#writemode

pid=spawn(command,[:out,:err]=>"/dev/null")#writemode

pid=spawn(command,3=>"/dev/null")#readmode

Forstdoutandstderr(andcombinationofthem),itisopenedinwritemode.Otherwisereadmodeisused.

Forspecifyingflagsandpermissionoffilecreationexplicitly,anarrayisusedinstead.

pid=spawn(command,:in=>["file"])#readmodeisassumed

pid=spawn(command,:in=>["file","r"])

pid=spawn(command,:out=>["log","w"])#0644assumed

pid=spawn(command,:out=>["log","w",0600])

pid=spawn(command,:out=>["log",File::WRONLY|File::

Thearrayspecifiesafilename,flagsandpermission.Theflagscanbeastringoraninteger.Iftheflagsisomittedornil,File::RDONLYisassumed.Thepermissionshouldbeaninteger.Ifthepermissionisomittedornil,0644isassumed.

IfanarrayofIOsandintegersarespecifiedasahashkey,alltheelementsareredirected.

#stdoutandstderrisredirectedtologfile.

#Thefile"log"isopenedjustonce.

pid=spawn(command,[:out,:err]=>["log","w"])

Anotherwaytomergemultiplefiledescriptorsis[:child,fd].[:child,fd]meansthefiledescriptorinthechildprocess.Thisisdifferentfromfd.Forexample,:err=>:outmeansredirectingchildstderrtoparentstdout.But:err=>[:child,:out]meansredirectingchildstderrtochildstdout.Theydifferifstdoutisredirectedinthechildprocessasfollows.

Page 619: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#stdoutandstderrisredirectedtologfile.

#Thefile"log"isopenedjustonce.

pid=spawn(command,:out=>["log","w"],:err=>[:child

[:child,:out]canbeusedtomergestderrintostdoutinIO.popen.Inthiscase,IO.popenredirectsstdouttoapipeinthechildprocessand[:child,:out]referstheredirectedstdout.

io=IO.popen(["sh","-c","echoout;echoerr>&2",:

pio.read#=>"out\nerr\n"

The:chdirkeyinoptionsspecifiesthecurrentdirectory.

pid=spawn(command,:chdir=>"/var/tmp")

spawnclosesallnon-standardunspecifieddescriptorsbydefault.The“standard”descriptorsare0,1and2.Thisbehaviorisspecifiedby:close_othersoption.:close_othersdoesn'taffectthestandarddescriptorswhichareclosedonlyif:closeisspecifiedexplicitly.

pid=spawn(command,:close_others=>true)#close3,4,5,...(default)

pid=spawn(command,:close_others=>false)#don'tclose3,4,5,...

:close_othersistruebydefaultforspawnandIO.popen.

Notethatfdswhichclose-on-execflagisalreadysetareclosedregardlessof:close_othersoption.

SoIO.pipeandspawncanbeusedasIO.popen.

#similartor=IO.popen(command)

r,w=IO.pipe

pid=spawn(command,:out=>w)#r,wisclosedinthechildprocess.

w.close

Page 620: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

:closeisspecifiedasahashvaluetocloseafdindividually.

f=open(foo)

system(command,f=>:close)#don'tinheritf.

Ifafiledescriptorneedtobeinherited,io=>iocanbeused.

#valgrindhas--log-fdoptionforlogdestination.

#log_w=>log_windicateslog_w.filenoinheritstochildprocess.

log_r,log_w=IO.pipe

pid=spawn("valgrind","--log-fd=#{log_w.fileno}","echo"

log_w.close

plog_r.read

Itisalsopossibletoexchangefiledescriptors.

pid=spawn(command,:out=>:err,:err=>:out)

Thehashkeysspecifyfiledescriptorsinthechildprocess.Thehashvaluesspecifiesfiledescriptorsintheparentprocess.Sotheabovespecifiesexchangingstdoutandstderr.Internally,spawnusesanextrafiledescriptortoresolvesuchcyclicfiledescriptormapping.

SeeKernel.execforthestandardshell.

ReturnsaTmsstructure(seeProcess::Tms)thatcontainsuserandsystemCPUtimesforthisprocess,andalsoforchildrenprocesses.

t=Process.times

[t.utime,t.stime,t.cutime,t.cstime]#=>[0.0,0.02,0.00,0.00]

times→aProcessTms

Page 621: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthe(real)userIDofthisprocess.

Process.uid#=>501

Setsthe(user)userIDforthisprocess.Notavailableonallplatforms.

Waitsforachildprocesstoexit,returnsitsprocessid,andsets$?toaProcess::Statusobjectcontaininginformationonthatprocess.Whichchilditwaitsondependsonthevalueofpid:

>0WaitsforthechildwhoseprocessIDequalspid.

0WaitsforanychildwhoseprocessgroupIDequalsthatofthecallingprocess.

-1Waitsforanychildprocess(thedefaultifnopidisgiven).

<-1WaitsforanychildwhoseprocessgroupIDequalstheabsolutevalueofpid.

TheflagsargumentmaybealogicaloroftheflagvaluesProcess::WNOHANG(donotblockifnochild

uid→fixnumProcess::UID.rid→fixnumProcess::Sys.getuid→fixnum

uid=user→numeric

wait()→fixnumwait(pid=-1,flags=0)→fixnumwaitpid(pid=-1,flags=0)→fixnum

Page 622: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

available)orProcess::WUNTRACED(returnstoppedchildrenthathaven'tbeenreported).Notallflagsareavailableonallplatforms,butaflagvalueofzerowillworkonallplatforms.

CallingthismethodraisesaSystemCallErroriftherearenochildprocesses.Notavailableonallplatforms.

includeProcess

fork{exit99}#=>27429

wait#=>27429

$?.exitstatus#=>99

pid=fork{sleep3}#=>27440

Time.now#=>2008-03-0819:56:16+0900

waitpid(pid,Process::WNOHANG)#=>nil

Time.now#=>2008-03-0819:56:16+0900

waitpid(pid,0)#=>27440

Time.now#=>2008-03-0819:56:19+0900

Waitsforachildprocesstoexit(see::waitpidforexactsemantics)andreturnsanarraycontainingtheprocessidandtheexitstatus(aProcess::Statusobject)ofthatchild.RaisesaSystemCallErroriftherearenochildprocesses.

Process.fork{exit99}#=>27437

pid,status=Process.wait2

pid#=>27437

status.exitstatus#=>99

Waitsforallchildren,returninganarrayofpid/statuspairs(wherestatusisaProcess::Statusobject).

fork{sleep0.2;exit2}#=>27432

wait2(pid=-1,flags=0)→[pid,status]waitpid2(pid=-1,flags=0)→[pid,status]

waitall→[[pid1,status1],...]

Page 623: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

fork{sleep0.1;exit1}#=>27433

fork{exit0}#=>27434

pProcess.waitall

produces:

[[30982,#<Process::Status:pid30982exit0>],

[30979,#<Process::Status:pid30979exit1>],

[30976,#<Process::Status:pid30976exit2>]]

Waitsforachildprocesstoexit,returnsitsprocessid,andsets$?toaProcess::Statusobjectcontaininginformationonthatprocess.Whichchilditwaitsondependsonthevalueofpid:

>0WaitsforthechildwhoseprocessIDequalspid.

0WaitsforanychildwhoseprocessgroupIDequalsthatofthecallingprocess.

-1Waitsforanychildprocess(thedefaultifnopidisgiven).

<-1WaitsforanychildwhoseprocessgroupIDequalstheabsolutevalueofpid.

TheflagsargumentmaybealogicaloroftheflagvaluesProcess::WNOHANG(donotblockifnochildavailable)orProcess::WUNTRACED(returnstoppedchildrenthathaven'tbeenreported).Notallflagsareavailableonallplatforms,butaflagvalueofzerowillworkonallplatforms.

wait()→fixnumwait(pid=-1,flags=0)→fixnumwaitpid(pid=-1,flags=0)→fixnum

Page 624: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CallingthismethodraisesaSystemCallErroriftherearenochildprocesses.Notavailableonallplatforms.

includeProcess

fork{exit99}#=>27429

wait#=>27429

$?.exitstatus#=>99

pid=fork{sleep3}#=>27440

Time.now#=>2008-03-0819:56:16+0900

waitpid(pid,Process::WNOHANG)#=>nil

Time.now#=>2008-03-0819:56:16+0900

waitpid(pid,0)#=>27440

Time.now#=>2008-03-0819:56:19+0900

Waitsforachildprocesstoexit(see::waitpidforexactsemantics)andreturnsanarraycontainingtheprocessidandtheexitstatus(aProcess::Statusobject)ofthatchild.RaisesaSystemCallErroriftherearenochildprocesses.

Process.fork{exit99}#=>27437

pid,status=Process.wait2

pid#=>27437

status.exitstatus#=>99

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

wait2(pid=-1,flags=0)→[pid,status]waitpid2(pid=-1,flags=0)→[pid,status]

Page 625: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleProcess::GIDTheProcess::GIDmodulecontainsacollectionofmodulefunctionswhichcanbeusedtoportablyget,set,andswitchthecurrentprocess'sreal,effective,andsavedgroupIDs.

InFilesprocess.c

PublicClassMethods

Changethecurrentprocess'srealandeffectivegroupIDtothatspecifiedbygroup.ReturnsthenewgroupID.Notavailableonallplatforms.

[Process.gid,Process.egid]#=>[0,0]

Process::GID.change_privilege(33)#=>33

[Process.gid,Process.egid]#=>[33,33]

ReturnstheeffectivegroupIDforthisprocess.Notavailableonallplatforms.

Process.egid#=>500

Process::GID.change_privilege(group)→fixnum

egid→fixnumProcess::GID.eid→fixnumProcess::Sys.geteid→fixnum

Page 626: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GetthegroupIDbythename.Ifthegroupisnotfound,ArgumentErrorwillberaised.

Process::GID.from_name("wheel")#=>0

Process::GID.from_name("nosuchgroup")#=>can'tfindgroupfornosuchgroup(ArgumentError)

SettheeffectivegroupID,andifpossible,thesavedgroupIDoftheprocesstothegivengroup.ReturnstheneweffectivegroupID.Notavailableonallplatforms.

[Process.gid,Process.egid]#=>[0,0]

Process::GID.grant_privilege(31)#=>33

[Process.gid,Process.egid]#=>[0,33]

ExchangerealandeffectivegroupIDsandreturntheneweffectivegroupID.Notavailableonallplatforms.

[Process.gid,Process.egid]#=>[0,33]

Process::GID.re_exchange#=>0

[Process.gid,Process.egid]#=>[33,0]

ReturnstrueiftherealandeffectivegroupIDsofaprocessmaybeexchangedonthecurrentplatform.

Process::GID.from_name(name)→gid

Process::GID.grant_privilege(group)→fixnumProcess::GID.eid=group→fixnum

Process::GID.re_exchange→fixnum

Process::GID.re_exchangeable?→trueorfalse

Page 627: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthe(real)groupIDforthisprocess.

Process.gid#=>500

ReturnstrueifthecurrentplatformhassavedgroupIDfunctionality.

SwitchtheeffectiveandrealgroupIDsofthecurrentprocess.Ifablockisgiven,thegroupIDswillbeswitchedbackaftertheblockisexecuted.ReturnstheneweffectivegroupIDifcalledwithoutablock,andthereturnvalueoftheblockifoneisgiven.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

gid→fixnumProcess::GID.rid→fixnumProcess::Sys.getgid→fixnum

Process::GID.sid_available?→trueorfalse

Process::GID.switch→fixnumProcess::GID.switch{||block}→object

Page 628: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classProcess::StatusProcess::Statusencapsulatestheinformationonthestatusofarunningorterminatedsystemprocess.Thebuilt-invariable$?iseitherniloraProcess::Statusobject.

fork{exit99}#=>26557

Process.wait#=>26557

$?.class#=>Process::Status

$?.to_i#=>25344

$?>>8#=>99

$?.stopped?#=>false

$?.exited?#=>true

$?.exitstatus#=>99

Posixsystemsrecordinformationonprocessesusinga16-bitinteger.Thelowerbitsrecordtheprocessstatus(stopped,exited,signaled)andtheupperbitspossiblycontainadditionalinformation(forexampletheprogram'sreturncodeinthecaseofexitedprocesses).PreRuby1.8,thesebitswereexposeddirectlytotheRubyprogram.RubynowencapsulatestheseinaProcess::Statusobject.Tomaximizecompatibility,however,theseobjectsretainabit-orientedinterface.Inthedescriptionsthatfollow,whenwetalkabouttheintegervalueofstat,we'rereferringtothis16bitvalue.

InFiles

Page 629: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

process.c

ParentObject

PublicInstanceMethods

LogicalANDofthebitsinstatwithnum.

fork{exit0x37}

Process.wait

sprintf('%04x',$?.to_i)#=>"3700"

sprintf('%04x',$?&0x1e00)#=>"1600"

Returnstrueiftheintegervalueofstatequalsother.

Shiftthebitsinstatrightnumplaces.

fork{exit99}#=>26563

Process.wait#=>26563

$?.to_i#=>25344

$?>>8#=>99

Returnstrueifstatgeneratedacoredumpwhenitterminated.Notavailableonallplatforms.

stat&num→fixnum

stat==other→trueorfalse

stat>>num→fixnum

coredump?→trueorfalse

exited?→trueorfalse

Page 630: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifstatexitednormally(forexampleusinganexit()callorfinishingtheprogram).

Returnstheleastsignificanteightbitsofthereturncodeofstat.Onlyavailableifexited?istrue.

fork{}#=>26572

Process.wait#=>26572

$?.exited?#=>true

$?.exitstatus#=>0

fork{exit99}#=>26573

Process.wait#=>26573

$?.exited?#=>true

$?.exitstatus#=>99

Overridetheinspectionmethod.

system("false")

p$?.inspect#=>"#<Process::Status:pid12861exit1>"

ReturnstheprocessIDthatthisstatusobjectrepresents.

fork{exit}#=>26569

Process.wait#=>26569

$?.pid#=>26569

Returnstrueifstatterminatedbecauseofanuncaughtsignal.

exitstatus→fixnumornil

inspect→string

pid→fixnum

signaled?→trueorfalse

Page 631: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthisprocessisstopped.ThisisonlyreturnedifthecorrespondingwaitcallhadtheWUNTRACEDflagset.

Returnsthenumberofthesignalthatcausedstattostop(ornilifselfisnotstopped).

Returnstrueifstatissuccessful,falseifnot.Returnsnilifexited?isnottrue.

Returnsthenumberofthesignalthatcausedstattoterminate(ornilifselfwasnotterminatedbyanuncaughtsignal).

ReturnsthebitsinstatasaFixnum.Pokingaroundinthesebitsisplatformdependent.

fork{exit0xab}#=>26566

Process.wait#=>26566

sprintf('%04x',$?.to_i)#=>"ab00"

Showpidandexitstatusasastring.

system("false")

p$?.to_s#=>"pid12766exit1"

stopped?→trueorfalse

stopsig→fixnumornil

success?→true,falseornil

termsig→fixnumornil

to_i→fixnumto_int→fixnum

to_s→string

Page 632: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 633: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleProcess::SysTheProcess::SysmodulecontainsUIDandGIDfunctionswhichprovidedirectbindingstothesystemcallsofthesamenamesinsteadofthemore-portableversionsofthesamefunctionalityfoundintheProcess,Process::UID,andProcess::GIDmodules.

InFilesprocess.c

PublicClassMethods

ReturnstheeffectivegroupIDforthisprocess.Notavailableonallplatforms.

Process.egid#=>500

ReturnstheeffectiveuserIDforthisprocess.

Process.euid#=>501

egid→fixnumProcess::GID.eid→fixnumProcess::Sys.geteid→fixnum

euid→fixnumProcess::UID.eid→fixnumProcess::Sys.geteuid→fixnum

Page 634: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthe(real)groupIDforthisprocess.

Process.gid#=>500

Returnsthe(real)userIDofthisprocess.

Process.uid#=>501

Returnstrueiftheprocesswascreatedasaresultofanexecve(2)systemcallwhichhadeitherofthesetuidorsetgidbitsset(andextraprivilegesweregivenasaresult)orifithaschangedanyofitsreal,effectiveorsaveduserorgroupIDssinceitbeganexecution.

SettheeffectivegroupIDofthecallingprocesstogroup.Notavailableonallplatforms.

SettheeffectiveuserIDofthecallingprocesstouser.Notavailableonallplatforms.

gid→fixnumProcess::GID.rid→fixnumProcess::Sys.getgid→fixnum

uid→fixnumProcess::UID.rid→fixnumProcess::Sys.getuid→fixnum

Process::Sys.issetugid→trueorfalse

Process::Sys.setegid(group)→nil

Process::Sys.seteuid(user)→nil

Process::Sys.setgid(group)→nil

Page 635: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SetthegroupIDofthecurrentprocesstogroup.Notavailableonallplatforms.

Setsthe(group)realand/oreffectivegroupIDsofthecurrentprocesstoridandeid,respectively.Avalueof-1foreithermeanstoleavethatIDunchanged.Notavailableonallplatforms.

Setsthe(group)real,effective,andsaveduserIDsofthecurrentprocesstorid,eid,andsidrespectively.Avalueof-1foranyvaluemeanstoleavethatIDunchanged.Notavailableonallplatforms.

Setsthe(user)real,effective,andsaveduserIDsofthecurrentprocesstorid,eid,andsidrespectively.Avalueof-1foranyvaluemeanstoleavethatIDunchanged.Notavailableonallplatforms.

Setsthe(user)realand/oreffectiveuserIDsofthecurrentprocesstoridandeid,respectively.Avalueof-1foreithermeanstoleavethatIDunchanged.Notavailableonallplatforms.

SettherealgroupIDofthecallingprocesstogroup.Notavailableonallplatforms.

Process::Sys.setregid(rid,eid)→nil

Process::Sys.setresgid(rid,eid,sid)→nil

Process::Sys.setresuid(rid,eid,sid)→nil

Process::Sys.setreuid(rid,eid)→nil

Process::Sys.setrgid(group)→nil

Page 636: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SettherealuserIDofthecallingprocesstouser.Notavailableonallplatforms.

SettheuserIDofthecurrentprocesstouser.Notavailableonallplatforms.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Process::Sys.setruid(user)→nil

Process::Sys.setuid(user)→nil

Page 637: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleProcess::UIDTheProcess::UIDmodulecontainsacollectionofmodulefunctionswhichcanbeusedtoportablyget,set,andswitchthecurrentprocess'sreal,effective,andsaveduserIDs.

InFilesprocess.c

PublicClassMethods

Changethecurrentprocess'srealandeffectiveuserIDtothatspecifiedbyuser.ReturnsthenewuserID.Notavailableonallplatforms.

[Process.uid,Process.euid]#=>[0,0]

Process::UID.change_privilege(31)#=>31

[Process.uid,Process.euid]#=>[31,31]

ReturnstheeffectiveuserIDforthisprocess.

Process.euid#=>501

Process::UID.change_privilege(user)→fixnum

euid→fixnumProcess::UID.eid→fixnumProcess::Sys.geteuid→fixnum

Page 638: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GettheuserIDbythename.Iftheuserisnotfound,ArgumentErrorwillberaised.

Process::UID.from_name("root")#=>0

Process::UID.from_name("nosuchuser")#=>can'tfinduserfornosuchuser(ArgumentError)

SettheeffectiveuserID,andifpossible,thesaveduserIDoftheprocesstothegivenuser.ReturnstheneweffectiveuserID.Notavailableonallplatforms.

[Process.uid,Process.euid]#=>[0,0]

Process::UID.grant_privilege(31)#=>31

[Process.uid,Process.euid]#=>[0,31]

ExchangerealandeffectiveuserIDsandreturntheneweffectiveuserID.Notavailableonallplatforms.

[Process.uid,Process.euid]#=>[0,31]

Process::UID.re_exchange#=>0

[Process.uid,Process.euid]#=>[31,0]

ReturnstrueiftherealandeffectiveuserIDsofaprocessmaybeexchangedonthecurrentplatform.

Process::UID.from_name(name)→uid

Process::UID.grant_privilege(user)→fixnumProcess::UID.eid=user→fixnum

Process::UID.re_exchange→fixnum

Process::UID.re_exchangeable?→trueorfalse

uid→fixnumProcess::UID.rid→fixnum

Page 639: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthe(real)userIDofthisprocess.

Process.uid#=>501

ReturnstrueifthecurrentplatformhassaveduserIDfunctionality.

SwitchtheeffectiveandrealuserIDsofthecurrentprocess.Ifablockisgiven,theuserIDswillbeswitchedbackaftertheblockisexecuted.ReturnstheneweffectiveuserIDifcalledwithoutablock,andthereturnvalueoftheblockifoneisgiven.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Process::Sys.getuid→fixnum

Process::UID.sid_available?→trueorfalse

Process::UID.switch→fixnumProcess::UID.switch{||block}→object

Page 640: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classProcess::Waiter

InFilesprocess.c

ParentThread

PublicInstanceMethods

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

pid()

Page 641: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRandomRandomprovidesaninterfacetoRuby'spseudo-randomnumbergenerator,orPRNG.ThePRNGproducesadeterministicsequenceofbitswhichapproximatetruerandomness.Thesequencemayberepresentedbyintegers,floats,orbinarystrings.

Thegeneratormaybeinitializedwitheitherasystem-generatedoruser-suppliedseedvaluebyusing::srand.

Theclassmethod#randprovidesthebasefunctionalityofKernel#randalongwithbetterhandlingoffloatingpointvalues.ThesearebothinterfacestoRandom::DEFAULT,theRubysystemPRNG.

::newwillcreateanewPRNGwithastateindependentofRandom::DEFAULT,allowingmultiplegeneratorswithdifferentseedvaluesorsequencepositionstoexistsimultaneously.Randomobjectscanbemarshaled,allowingsequencestobesavedandresumed.

PRNGsarecurrentlyimplementedasamodifiedMersenneTwisterwithaperiodof2**19937-1.

InFiles

Page 642: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

random.c

ParentObject

Constants

DEFAULT

DirectaccesstoRuby'sPseudorandomnumbergenerator(PRNG).

PublicClassMethods

CreatesanewPRNGusingseedtosettheinitialstate.Ifseedisomitted,thegeneratorisinitializedwith::new_seed.

See::srandformoreinformationontheuseofseedvalues.

Returnsanarbitraryseedvalue.Thisisusedby::newwhennoseedvalueisspecifiedasanargument.

Random.new_seed#=>115032730400174366788466674494640623225

new(seed=Random.new_seed)→prng

new_seed→integer

rand→float

Page 643: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

AliasofRandom::DEFAULT.rand.

Seedsthesystempseudo-randomnumbergenerator,Random::DEFAULT,withnumber.Thepreviousseedvalueisreturned.

Ifnumberisomitted,seedsthegeneratorusingasourceofentropyprovidedbytheoperatingsystem,ifavailable(/dev/urandomonUnixsystemsortheRSAcryptographicprovideronWindows),whichisthencombinedwiththetime,theprocessid,andasequencenumber.

srandmaybeusedtoensurerepeatablesequencesofpseudo-randomnumbersbetweendifferentrunsoftheprogram.Bysettingtheseedtoaknownvalue,programscanbemadedeterministicduringtesting.

srand1234#=>268519324636777531569100071560086917274

[rand,rand]#=>[0.1915194503788923,0.6221087710398319]

[rand(10),rand(1000)]#=>[4,664]

srand1234#=>1234

[rand,rand]#=>[0.1915194503788923,0.6221087710398319]

PublicInstanceMethods

Returnstrueifthetwogeneratorshavethesameinternalstate,otherwisefalse.Equivalentgeneratorswillreturnthesamesequenceofpseudo-randomnumbers.Twogeneratorswillgenerallyhavethesamestateonlyiftheywereinitializedwiththesame

rand(max)→number

srand(number=Random.new_seed)→old_seed

prng1==prng2→trueorfalse

Page 644: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

seed

Random.new==Random.new#=>false

Random.new(1234)==Random.new(1234)#=>true

andhavethesameinvocationhistory.

prng1=Random.new(1234)

prng2=Random.new(1234)

prng1==prng2#=>true

prng1.rand#=>0.1915194503788923

prng1==prng2#=>false

prng2.rand#=>0.1915194503788923

prng1==prng2#=>true

Returnsarandombinarystringcontainingsizebytes.

random_string=Random.new.bytes(10)#=>"\xD7:R\xAB?\x83\xCE\xFAkO"

random_string.size#=>10

WhenmaxisanInteger,randreturnsarandomintegergreaterthanorequaltozeroandlessthanmax.UnlikeKernel#rand,whenmaxisanegativeintegerorzero,randraisesanArgumentError.

prng=Random.new

prng.rand(100)#=>42

WhenmaxisaFloat,randreturnsarandomfloatingpointnumberbetween0.0andmax,including0.0andexcludingmax.

prng.rand(1.5)#=>1.4600282860034115

bytes(size)→a_string

rand→floatrand(max)→number

Page 645: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

WhenmaxisaRange,randreturnsarandomnumberwhererange.member?(number)==true.

prng.rand(5..9)#=>oneof[5,6,7,8,9]

prng.rand(5...9)#=>oneof[5,6,7,8]

prng.rand(5.0..9.0)#=>between5.0and9.0,including9.0

prng.rand(5.0...9.0)#=>between5.0and9.0,excluding9.0

Boththebeginningandendingvaluesoftherangemustrespondtosubtract(-)andadd(+)methods,orrandwillraiseanArgumentError.

Returnstheseedvalueusedtoinitializethegenerator.Thismaybeusedtoinitializeanothergeneratorwiththesamestateatalatertime,causingittoproducethesamesequenceofnumbers.

prng1=Random.new(1234)

prng1.seed#=>1234

prng1.rand(100)#=>47

prng2=Random.new(prng1.seed)

prng2.rand(100)#=>47

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

seed→integer

Page 646: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRangeARangerepresentsaninterval—asetofvalueswithabeginningandanend.Rangesmaybeconstructedusingthes..eands...eliterals,orwith::new.Rangesconstructedusing..runfromthebeginningtotheendinclusively.Thosecreatedusing...excludetheendvalue.Whenusedasaniterator,rangesreturneachvalueinthesequence.

(-1..-5).to_a#=>[]

(-5..-1).to_a#=>[-5,-4,-3,-2,-1]

('a'..'e').to_a#=>["a","b","c","d","e"]

('a'...'e').to_a#=>["a","b","c","d"]

Page 647: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CustomObjectsinRanges

Rangescanbeconstructedusinganyobjectsthatcanbecomparedusingthe<=>operator.Methodsthattreattherangeasasequence(eachandmethodsinheritedfromEnumerable)expectthebeginobjecttoimplementasuccmethodtoreturnthenextobjectinsequence.Thestepandinclude?methodsrequirethebeginobjecttoimplementsuccortobenumeric.

IntheXsclassbelowboth<=>andsuccareimplementedsoXscanbeusedtoconstructranges.NotethattheComparablemoduleisincludedsothe==methodisdefinedintermsof<=>.

classXs#representastringof'x's

includeComparable

attr:length

definitialize(n)

@length=n

end

defsucc

Xs.new(@length+1)

end

def<=>(other)

@length<=>other.length

end

defto_s

sprintf"%2d#{inspect}",@length

end

definspect

'x'*@length

end

Page 648: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

AnexampleofusingXstoconstructarange:

r=Xs.new(3)..Xs.new(6)#=>xxx..xxxxxx

r.to_a#=>[xxx,xxxx,xxxxx,xxxxxx]

r.member?(Xs.new(5))#=>true

InFilesrange.c

ParentObject

IncludedModulesEnumerable

PublicClassMethods

Constructsarangeusingthegivenbeginandend.Iftheexclude_endparameterisomittedorisfalse,therngwillincludetheendobject;otherwise,itwillbeexcluded.

PublicInstanceMethods

new(begin,end,exclude_end=false)→rng

Page 649: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstrueonlyifobjisaRange,hasequivalentbeginandenditems(bycomparingthemwith==),andhasthesameexclude_end?settingastherange.

(0..2)==(0..2)#=>true

(0..2)==Range.new(0,2)#=>true

(0..2)==(0...2)#=>false

Returnstrueifobjisanelementoftherange,falseotherwise.Conveniently,===isthecomparisonoperatorusedbycasestatements.

case79

when1..50thenprint"low\n"

when51..75thenprint"medium\n"

when76..100thenprint"high\n"

end

produces:

high

Returnstheobjectthatdefinesthebeginningoftherange.

(1..10).begin#=>1

Byusingbinarysearch,findsavalueinrangewhichmeetsthegivenconditioninO(logn)wherenisthesizeoftherange.

rng==obj→trueorfalse

rng===obj→trueorfalse

begin→obj

bsearch{|obj|block}→value

Page 650: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Youcanusethismethodintwousecases:afind-minimummodeandafind-anymode.Ineithercase,theelementsoftherangemustbemonotone(orsorted)withrespecttotheblock.

Infind-minimummode(thisisagoodchoicefortypicalusecase),theblockmustreturntrueorfalse,andtheremustbeavaluexsothat:

theblockreturnsfalseforanyvaluewhichislessthanx,and

theblockreturnstrueforanyvaluewhichisgreaterthanorequaltox.

Ifxiswithintherange,thismethodreturnsthevaluex.Otherwise,itreturnsnil.

ary=[0,4,7,10,12]

(0...ary.size).bsearch{|i|ary[i]>=4}#=>1

(0...ary.size).bsearch{|i|ary[i]>=6}#=>2

(0...ary.size).bsearch{|i|ary[i]>=8}#=>3

(0...ary.size).bsearch{|i|ary[i]>=100}#=>nil

(0.0...Float::INFINITY).bsearch{|x|Math.log(x)>=0}

Infind-anymode(thisbehaveslikelibc'sbsearch(3)),theblockmustreturnanumber,andtheremustbetwovaluesxandy(x<=y)sothat:

theblockreturnsapositivenumberforvifv<x,

theblockreturnszeroforvifx<=v<y,and

theblockreturnsanegativenumberforvify<=v.

Thismethodreturnsanyvaluewhichiswithintheintersectionofthegivenrangeandx…y(ifany).Ifthereisnovaluethatsatisfiesthecondition,itreturnsnil.

Page 651: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ary=[0,100,100,100,200]

(0..4).bsearch{|i|100-ary[i]}#=>1,2or3

(0..4).bsearch{|i|300-ary[i]}#=>nil

(0..4).bsearch{|i|50-ary[i]}#=>nil

Youmustnotmixthetwomodesatatime;theblockmustalwaysreturneithertrue/false,oralwaysreturnanumber.Itisundefinedwhichvalueisactuallypickedupateachiteration.

Returnstrueifobjisbetweenthebeginandendoftherange.

Thistestsbegin<=obj<=endwhenexclude_end?isfalseandbegin<=obj<endwhenexclude_end?istrue.

("a".."z").cover?("c")#=>true

("a".."z").cover?("5")#=>false

("a".."z").cover?("cc")#=>true

Iteratesovertheelementsofrange,passingeachinturntotheblock.

Theeachmethodcanonlybeusedifthebeginobjectoftherangesupportsthesuccmethod.ATypeErrorisraisediftheobjectdoesnothavesuccmethoddefined(likeFloat).

Ifnoblockisgiven,anenumeratorisreturnedinstead.

(10..15).each{|n|printn,''}

#prints:101112131415

cover?(obj)→trueorfalse

each{|i|block}→rngeach→an_enumerator

Page 652: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(2.5..5).each{|n|printn,''}

#raises:TypeError:can'titeratefromFloat

Returnstheobjectthatdefinestheendoftherange.

(1..10).end#=>10

(1...10).end#=>10

ReturnstrueonlyifobjisaRange,hasequivalentbeginandenditems(bycomparingthemwitheql?),andhasthesameexclude_end?settingastherange.

(0..2).eql?(0..2)#=>true

(0..2).eql?(Range.new(0,2))#=>true

(0..2).eql?(0...2)#=>false

Returnstrueiftherangeexcludesitsendvalue.

(1..5).exclude_end?#=>false

(1...5).exclude_end?#=>true

Returnsthefirstobjectintherange,oranarrayofthefirstnelements.

(10..20).first#=>10

(10..20).first(3)#=>[10,11,12]

end→obj

eql?(obj)→trueorfalse

exclude_end?→trueorfalse

first→objfirst(n)→an_array

Page 653: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Computeahash-codeforthisrange.Tworangeswithequalbeginandendpoints(usingeql?),andthesameexclude_end?valuewillgeneratethesamehash-code.

SeealsoObject#hash.

Returnstrueifobjisanelementoftherange,falseotherwise.Ifbeginandendarenumeric,comparisonisdoneaccordingtothemagnitudeofthevalues.

("a".."z").include?("g")#=>true

("a".."z").include?("A")#=>false

("a".."z").include?("cc")#=>false

Convertthisrangeobjecttoaprintableform(usinginspecttoconvertthebeginandendobjects).

Returnsthelastobjectintherange,oranarrayofthelastnelements.

Notethatwithnoargumentslastwillreturntheobjectthatdefinestheendoftherangeevenifexclude_end?istrue.

(10..20).last#=>20

(10...20).last#=>20

(10..20).last(3)#=>[18,19,20]

(10...20).last(3)#=>[17,18,19]

hash→fixnum

member?(obj)→trueorfalseinclude?(obj)→trueorfalse

inspect→string

last→objlast(n)→an_array

Page 654: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthemaximumvalueintherange.Returnsnilifthebeginvalueoftherangelargerthantheendvalue.

Canbegivenanoptionalblocktooverridethedefaultcomparisonmethoda<=>b.

(10..20).max#=>20

Returnstrueifobjisanelementoftherange,falseotherwise.Ifbeginandendarenumeric,comparisonisdoneaccordingtothemagnitudeofthevalues.

("a".."z").include?("g")#=>true

("a".."z").include?("A")#=>false

("a".."z").include?("cc")#=>false

Returnstheminimumvalueintherange.Returnsnilifthebeginvalueoftherangeislargerthantheendvalue.

Canbegivenanoptionalblocktooverridethedefaultcomparisonmethoda<=>b.

max→objmax{|a,b|block}→objmax(n)→objmax(n){|a,b|block}→obj

member?(obj)→trueorfalseinclude?(obj)→trueorfalse

min→objmin{|a,b|block}→objmin(n)→arraymin(n){|a,b|block}→array

Page 655: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

(10..20).min#=>10

Returnsthenumberofelementsintherange.BoththebeginandtheendoftheRangemustbeNumeric,otherwisenilisreturned.

(10..20).size#=>11

('a'..'z').size#=>nil

(-Float::INFINITY..Float::INFINITY).size#=>Infinity

Iteratesovertherange,passingeachnthelementtotheblock.Ifbeginandendarenumeric,nisaddedforeachiteration.Otherwisestepinvokessucctoiteratethroughrangeelements.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

range=Xs.new(1)..Xs.new(10)

range.step(2){|x|putsx}

puts

range.step(3){|x|putsx}

produces:

1x

3xxx

5xxxxx

7xxxxxxx

9xxxxxxxxx

1x

4xxxx

7xxxxxxx

10xxxxxxxxxx

size→num

step(n=1){|obj|block}→rngstep(n=1)→an_enumerator

Page 656: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SeeRangeforthedefinitionofclassXs.

Convertthisrangeobjecttoaprintableform(usingto_stoconvertthebeginandendobjects).

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

to_s→string

Page 657: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRangeErrorRaisedwhenagivennumericalvalueisoutofrange.

[1,2,3].drop(1<<100)

raisestheexception:

RangeError:bignumtoobigtoconvertinto`long'

InFileserror.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 658: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRationalArationalnumbercanberepresentedasapairedintegernumber;a/b(b>0).Whereaisnumeratorandbisdenominator.Integeraequalsrationala/1mathematically.

Inruby,youcancreaterationalobjectwithRational,#to_r,rationalizemethodorsuffixingrtoaliteral.Thereturnvalueswillbeirreducible.

Rational(1)#=>(1/1)

Rational(2,3)#=>(2/3)

Rational(4,-6)#=>(-2/3)

3.to_r#=>(3/1)

2/3r#=>(2/3)

Youcanalsocreaterationalobjectfromfloating-pointnumbersorstrings.

Rational(0.3)#=>(5404319552844595/18014398509481984)

Rational('0.3')#=>(3/10)

Rational('2/3')#=>(2/3)

0.3.to_r#=>(5404319552844595/18014398509481984)

'0.3'.to_r#=>(3/10)

'2/3'.to_r#=>(2/3)

0.3.rationalize#=>(3/10)

Arationalobjectisanexactnumber,whichhelpsyoutowriteprogramwithoutanyroundingerrors.

Page 659: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

10.times.inject(0){|t,|t+0.1}#=>0.9999999999999999

10.times.inject(0){|t,|t+Rational('0.1')}#=>(1/1)

However,whenanexpressionhasinexactfactor(numericalvalueoroperation),willproduceaninexactresult.

Rational(10)/3#=>(10/3)

Rational(10)/3.0#=>3.3333333333333335

Rational(-8)**Rational(1,3)

#=>(1.0000000000000002+1.7320508075688772i)

InFilesrational.c

ParentNumeric

PublicInstanceMethods

Performsmultiplication.

Rational(2,3)*Rational(2,3)#=>(4/9)

Rational(900)*Rational(1)#=>(900/1)

Rational(-2,9)*Rational(-9,2)#=>(1/1)

Rational(9,8)*4#=>(9/2)

Rational(20,9)*9.8#=>21.77777777777778

rat*numeric→numeric

Page 660: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Performsexponentiation.

Rational(2)**Rational(3)#=>(8/1)

Rational(10)**-2#=>(1/100)

Rational(10)**-2.0#=>0.01

Rational(-4)**Rational(1,2)#=>(1.2246063538223773e-16+2.0i)

Rational(1,2)**0#=>(1/1)

Rational(1,2)**0.0#=>1.0

Performsaddition.

Rational(2,3)+Rational(2,3)#=>(4/3)

Rational(900)+Rational(1)#=>(900/1)

Rational(-2,9)+Rational(-9,2)#=>(-85/18)

Rational(9,8)+4#=>(41/8)

Rational(20,9)+9.8#=>12.022222222222222

Performssubtraction.

Rational(2,3)-Rational(2,3)#=>(0/1)

Rational(900)-Rational(1)#=>(899/1)

Rational(-2,9)-Rational(-9,2)#=>(77/18)

Rational(9,8)-4#=>(23/8)

Rational(20,9)-9.8#=>-7.577777777777778

Performsdivision.

Rational(2,3)/Rational(2,3)#=>(1/1)

Rational(900)/Rational(1)#=>(900/1)

Rational(-2,9)/Rational(-9,2)#=>(4/81)

Rational(9,8)/4#=>(9/32)

rat**numeric→numeric

rat+numeric→numeric

rat-numeric→numeric

rat/numeric→numericquo(numeric)→numeric

Page 661: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Rational(20,9)/9.8#=>0.22675736961451246

Performscomparisonandreturns-1,0,or+1.

nilisreturnedifthetwovaluesareincomparable.

Rational(2,3)<=>Rational(2,3)#=>0

Rational(5)<=>5#=>0

Rational(2,3)<=>Rational(1,3)#=>1

Rational(1,3)<=>1#=>-1

Rational(1,3)<=>0.3#=>1

Returnstrueifratequalsobjectnumerically.

Rational(2,3)==Rational(2,3)#=>true

Rational(5)==5#=>true

Rational(0)==0.0#=>true

Rational('1/3')==0.33#=>false

Rational('1/2')=='1/2'#=>false

Returnsthetruncatedvalue(towardpositiveinfinity).

Rational(3).ceil#=>3

Rational(2,3).ceil#=>1

Rational(-3,2).ceil#=>-1

decimal-123.456

^^^^^^

precision-3-2-10+1+2

'%f'%Rational('-123.456').ceil(+1)#=>"-123.400000"

'%f'%Rational('-123.456').ceil(-1)#=>"-120.000000"

rational<=>numeric→-1,0,+1ornil

rat==object→trueorfalse

ceil→integerceil(precision=0)→rational

Page 662: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthedenominator(alwayspositive).

Rational(7).denominator#=>1

Rational(7,1).denominator#=>1

Rational(9,-4).denominator#=>4

Rational(-2,-10).denominator#=>5

rat.numerator.gcd(rat.denominator)#=>1

Performsdivisionandreturnsthevalueasafloat.

Rational(2,3).fdiv(1)#=>0.6666666666666666

Rational(2,3).fdiv(0.5)#=>1.3333333333333333

Rational(2).fdiv(3)#=>0.6666666666666666

Returnsthetruncatedvalue(towardnegativeinfinity).

Rational(3).floor#=>3

Rational(2,3).floor#=>0

Rational(-3,2).floor#=>-1

decimal-123.456

^^^^^^

precision-3-2-10+1+2

'%f'%Rational('-123.456').floor(+1)#=>"-123.500000"

'%f'%Rational('-123.456').floor(-1)#=>"-130.000000"

Returnsthevalueasastringforinspection.

Rational(2).inspect#=>"(2/1)"

Rational(-8,6).inspect#=>"(-4/3)"

Rational('1/2').inspect#=>"(1/2)"

denominator→integer

fdiv(numeric)→float

floor→integerfloor(precision=0)→rational

inspect→string

Page 663: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthenumerator.

Rational(7).numerator#=>7

Rational(7,1).numerator#=>7

Rational(9,-4).numerator#=>-9

Rational(-2,-10).numerator#=>1

Performsdivision.

Rational(2,3)/Rational(2,3)#=>(1/1)

Rational(900)/Rational(1)#=>(900/1)

Rational(-2,9)/Rational(-9,2)#=>(4/81)

Rational(9,8)/4#=>(9/32)

Rational(20,9)/9.8#=>0.22675736961451246

Returnsasimplerapproximationofthevalueiftheoptionalargumentepsisgiven(rat-|eps|<=result<=rat+|eps|),selfotherwise.

r=Rational(5033165,16777216)

r.rationalize#=>(5033165/16777216)

r.rationalize(Rational('0.01'))#=>(3/10)

r.rationalize(Rational('0.1'))#=>(1/3)

Returnsthetruncatedvalue(towardthenearestinteger;0.5=>1;-0.5=>-1).

numerator→integer

rat/numeric→numericquo(numeric)→numeric

rationalize→selfrationalize(eps)→rational

round→integerround(precision=0)→rational

Page 664: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Rational(3).round#=>3

Rational(2,3).round#=>1

Rational(-3,2).round#=>-2

decimal-123.456

^^^^^^

precision-3-2-10+1+2

'%f'%Rational('-123.456').round(+1)#=>"-123.500000"

'%f'%Rational('-123.456').round(-1)#=>"-120.000000"

Returnthevalueasafloat.

Rational(2).to_f#=>2.0

Rational(9,4).to_f#=>2.25

Rational(-3,4).to_f#=>-0.75

Rational(20,3).to_f#=>6.666666666666667

Returnsthetruncatedvalueasaninteger.

Equivalentto

rat.truncate.

Rational(2,3).to_i#=>0

Rational(3).to_i#=>3

Rational(300.6).to_i#=>300

Rational(98,71).to_i#=>1

Rational(-30,2).to_i#=>-15

Returnsself.

Rational(2).to_r#=>(2/1)

Rational(-8,6).to_r#=>(-4/3)

to_f→float

to_i→integer

to_r→self

Page 665: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthevalueasastring.

Rational(2).to_s#=>"2/1"

Rational(-8,6).to_s#=>"-4/3"

Rational('1/2').to_s#=>"1/2"

Returnsthetruncatedvalue(towardzero).

Rational(3).truncate#=>3

Rational(2,3).truncate#=>0

Rational(-3,2).truncate#=>-1

decimal-123.456

^^^^^^

precision-3-2-10+1+2

'%f'%Rational('-123.456').truncate(+1)#=>"-123.400000"

'%f'%Rational('-123.456').truncate(-1)#=>"-120.000000"

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

to_s→string

truncate→integertruncate(precision=0)→rational

Page 666: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRational::compatible

InFilesrational.c

ParentObject

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 667: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRegexpARegexpholdsaregularexpression,usedtomatchapatternagainststrings.Regexpsarecreatedusingthe/.../and%r{...}literals,andbytheRegexp::newconstructor.

Regularexpressions(regexps)arepatternswhichdescribethecontentsofastring.They'reusedfortestingwhetherastringcontainsagivenpattern,orextractingtheportionsthatmatch.Theyarecreatedwiththe/pat/and%r{pat}literalsortheRegexp.newconstructor.

Aregexpisusuallydelimitedwithforwardslashes(/).Forexample:

/hay/=~'haystack'#=>0

/y/.match('haystack')#=>#<MatchData"y">

Ifastringcontainsthepatternitissaidtomatch.Aliteralstringmatchesitself.

Here'haystack'doesnotcontainthepattern'needle',soitdoesn'tmatch:

/needle/.match('haystack')#=>nil

Here'haystack'containsthepattern'hay',soitmatches:

Page 668: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

/hay/.match('haystack')#=>#<MatchData"hay">

Specifically,/st/requiresthatthestringcontainsthelettersfollowedbythelettert,soitmatcheshaystack,also.

Page 669: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

=~and#match

Patternmatchingmaybeachievedbyusing=~operatoror#matchmethod.

=~operator

=~isRuby'sbasicpattern-matchingoperator.Whenoneoperandisaregularexpressionandtheotherisastringthentheregularexpressionisusedasapatterntomatchagainstthestring.(ThisoperatorisequivalentlydefinedbyRegexpandStringsotheorderofStringandRegexpdonotmatter.Otherclassesmayhavedifferentimplementationsof=~.)Ifamatchisfound,theoperatorreturnsindexoffirstmatchinstring,otherwiseitreturnsnil.

/hay/=~'haystack'#=>0

'haystack'=~/hay/#=>0

/a/=~'haystack'#=>1

/u/=~'haystack'#=>nil

Using=~operatorwithaStringandRegexpthe$~globalvariableissetafterasuccessfulmatch.$~holdsaMatchDataobject.::last_matchisequivalentto$~.

#matchmethod

ThematchmethodreturnsaMatchDataobject:

Page 670: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

/st/.match('haystack')#=>#<MatchData"st">

Page 671: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

MetacharactersandEscapes

Thefollowingaremetacharacters(,),[,],{,},.,?,+,*.Theyhaveaspecificmeaningwhenappearinginapattern.Tomatchthemliterallytheymustbebackslash-escaped.Tomatchabackslashliterallybackslash-escapethat:<tt>\\</tt>.

/1\+2=3\?/.match('Does1+2=3?')#=>#<MatchData"1+2=3?">

Patternsbehavelikedouble-quotedstringssocancontainthesamebackslashescapes.

/\s\u{67714eac90fd}/.match("Goto東京都")#=>#<MatchData"東京都">

ArbitraryRubyexpressionscanbeembeddedintopatternswiththe#{...}construct.

place="東京都"/#{place}/.match("Goto東京都")#=>#<MatchData"東京都">

Page 672: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CharacterClasses

Acharacterclassisdelimitedwithsquarebrackets([,])andlistscharactersthatmayappearatthatpointinthematch./[ab]/meansaorb,asopposedto/ab/whichmeansafollowedbyb.

/W[aeiou]rd/.match("Word")#=>#<MatchData"Word">

Withinacharacterclassthehyphen(-)isametacharacterdenotinganinclusiverangeofcharacters.[abcd]isequivalentto[a-d].Arangecanbefollowedbyanotherrange,so[abcdwxyz]isequivalentto[a-dw-z].Theorderinwhichrangesorindividualcharactersappearinsideacharacterclassisirrelevant.

/[0-9a-f]/.match('9f')#=>#<MatchData"9">

/[9f]/.match('9f')#=>#<MatchData"9">

Ifthefirstcharacterofacharacterclassisacaret(^)theclassisinverted:itmatchesanycharacterexceptthosenamed.

/[^a-eg-z]/.match('f')#=>#<MatchData"f">

Acharacterclassmaycontainanothercharacterclass.Byitselfthisisn'tusefulbecause[a-z[0-9]]describesthesamesetas[a-z0-9].

Page 673: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

However,characterclassesalsosupportthe&&operatorwhichperformssetintersectiononitsarguments.Thetwocanbecombinedasfollows:

/[a-w&&[^c-g]z]/#([a-w]AND([^c-g]ORz))

Thisisequivalentto:

/[abh-w]/

Thefollowingmetacharactersalsobehavelikecharacterclasses:

/./-Anycharacterexceptanewline././m-Anycharacter(themmodifierenablesmultilinemode)/\w/-Awordcharacter([a-zA-Z0-9_])/\W/-Anon-wordcharacter([^a-zA-Z0-9_]).PleasetakealookatBug#4044ifusing/\W/withthe/imodifier./\d/-Adigitcharacter([0-9])/\D/-Anon-digitcharacter([^0-9])/\h/-Ahexdigitcharacter([0-9a-fA-F])/\H/-Anon-hexdigitcharacter([^0-9a-fA-F])/\s/-Awhitespacecharacter:/[\t\r\n\f]//\S/-Anon-whitespacecharacter:/[^\t\r\n\f]/

Page 674: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

POSIXbracketexpressionsarealsosimilartocharacterclasses.Theyprovideaportablealternativetotheabove,withtheaddedbenefitthattheyencompassnon-ASCIIcharacters.Forinstance,/\d/matchesonlytheASCIIdecimaldigits(0-9);whereas/[[:digit:]]/matchesanycharacterintheUnicodeNdcategory.

/[[:alnum:]]/-Alphabeticandnumericcharacter/[[:alpha:]]/-Alphabeticcharacter/[[:blank:]]/-Spaceortab/[[:cntrl:]]/-Controlcharacter/[[:digit:]]/-Digit/[[:graph:]]/-Non-blankcharacter(excludesspaces,controlcharacters,andsimilar)/[[:lower:]]/-Lowercasealphabeticalcharacter/[[:print:]]/-Like[:graph:],butincludesthespacecharacter/[[:punct:]]/-Punctuationcharacter/[[:space:]]/-Whitespacecharacter([:blank:],newline,carriagereturn,etc.)/[[:upper:]]/-Uppercasealphabetical/[[:xdigit:]]/-Digitallowedinahexadecimalnumber(i.e.,0-9a-fA-F)

Rubyalsosupportsthefollowingnon-POSIXcharacterclasses:

Page 675: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

/[[:word:]]/-AcharacterinoneofthefollowingUnicodegeneralcategoriesLetter,Mark,Number,Connector_Punctuation/[[:ascii:]]/-AcharacterintheASCIIcharacterset

#U+06F2is"EXTENDEDARABIC-INDICDIGITTWO"

/[[:digit:]]/.match("\u06F2")#=>#<MatchData"\u{06F2}">

/[[:upper:]][[:lower:]]/.match("Hello")#=>#<MatchData"He">

/[[:xdigit:]][[:xdigit:]]/.match("A6")#=>#<MatchData"A6">

Page 676: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Repetition

Theconstructsdescribedsofarmatchasinglecharacter.Theycanbefollowedbyarepetitionmetacharactertospecifyhowmanytimestheyneedtooccur.Suchmetacharactersarecalledquantifiers.

*-Zeroormoretimes+-Oneormoretimes?-Zerooronetimes(optional){n}-Exactlyntimes{n,}-normoretimes{,m}-morlesstimes{n,m}-Atleastnandatmostmtimes

Atleastoneuppercasecharacter('H'),atleastonelowercasecharacter('e'),two'l'characters,thenone'o':

"Hello".match(/[[:upper:]]+[[:lower:]]+l{2}o/)#=>#<MatchData"Hello">

Repetitionisgreedybydefault:asmanyoccurrencesaspossiblearematchedwhilestillallowingtheoverallmatchtosucceed.Bycontrast,lazymatchingmakestheminimalamountofmatchesnecessaryforoverallsuccess.Agreedymetacharactercanbemadelazybyfollowingitwith?.

Page 677: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Bothpatternsbelowmatchthestring.Thefirstusesagreedyquantifierso'.+'matches'<a><b>';thesecondusesalazyquantifierso'.+?'matches'<a>':

/<.+>/.match("<a><b>")#=>#<MatchData"<a><b>">

/<.+?>/.match("<a><b>")#=>#<MatchData"<a>">

Aquantifierfollowedby+matchespossessively:onceithasmatcheditdoesnotbacktrack.Theybehavelikegreedyquantifiers,buthavingmatchedtheyrefuseto“giveup”theirmatchevenifthisjeopardisestheoverallmatch.

Page 678: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Capturing

Parenthesescanbeusedforcapturing.Thetextenclosedbythen<sup>th</sup>groupofparenthesescanbesubsequentlyreferredtowithn.Withinapatternusethebackreference\n;outsideofthepatternuseMatchData[n].

'at'iscapturedbythefirstgroupofparentheses,thenreferredtolaterwith\1:

/[csh](..)[csh]\1in/.match("Thecatsatinthehat"

#=>#<MatchData"catsatin"1:"at">

#matchreturnsaMatchDataobjectwhichmakesthecapturedtextavailablewithits#[]method:

/[csh](..)[csh]\1in/.match("Thecatsatinthehat"

Capturegroupscanbereferredtobynamewhendefinedwiththe(?<name>)or(?'name')constructs.

/\$(?<dollars>\d+)\.(?<cents>\d+)/.match("$3.67")

=>#<MatchData"$3.67"dollars:"3"cents:"67">

/\$(?<dollars>\d+)\.(?<cents>\d+)/.match("$3.67")[:

Namedgroupscanbebackreferencedwith\k<name>,wherenameisthegroupname.

Page 679: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

/(?<vowel>[aeiou]).\k<vowel>.\k<vowel>/.match('ototomy'

#=>#<MatchData"ototo"vowel:"o">

Note:Aregexpcan'tusenamedbackreferencesandnumberedbackreferencessimultaneously.

Whennamedcapturegroupsareusedwithaliteralregexpontheleft-handsideofanexpressionandthe=~operator,thecapturedtextisalsoassignedtolocalvariableswithcorrespondingnames.

/\$(?<dollars>\d+)\.(?<cents>\d+)/=~"$3.67"#=>0

dollars#=>"3"

Page 680: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Grouping

Parenthesesalsogroupthetermstheyenclose,allowingthemtobequantifiedasoneatomicwhole.

Thepatternbelowmatchesavowelfollowedby2wordcharacters:

/[aeiou]\w{2}/.match("Caenorhabditiselegans")#=>#<MatchData"aen">

Whereasthefollowingpatternmatchesavowelfollowedbyawordcharacter,twice,i.e.[aeiou]\w[aeiou]\w:'enor'.

/([aeiou]\w){2}/.match("Caenorhabditiselegans")

#=>#<MatchData"enor"1:"or">

The(?:…)constructprovidesgroupingwithoutcapturing.Thatis,itcombinesthetermsitcontainsintoanatomicwholewithoutcreatingabackreference.Thisbenefitsperformanceattheslightexpenseofreadability.

Thefirstgroupofparenthesescaptures'n'andthesecond'ti'.Thesecondgroupisreferredtolaterwiththebackreference\2:

/I(n)ves(ti)ga\2ons/.match("Investigations")

#=>#<MatchData"Investigations"1:"n"2:"ti">

Page 681: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thefirstgroupofparenthesesisnowmadenon-capturingwith'?:',soitstillmatches'n',butdoesn'tcreatethebackreference.Thus,thebackreference\1nowrefersto'ti'.

/I(?:n)ves(ti)ga\1ons/.match("Investigations")

#=>#<MatchData"Investigations"1:"ti">

AtomicGrouping

Groupingcanbemadeatomicwith(?>pat).Thiscausesthesubexpressionpattobematchedindependentlyoftherestoftheexpressionsuchthatwhatitmatchesbecomesfixedfortheremainderofthematch,unlesstheentiresubexpressionmustbeabandonedandsubsequentlyrevisited.Inthiswaypatistreatedasanon-divisiblewhole.Atomicgroupingistypicallyusedtooptimisepatternssoastopreventtheregularexpressionenginefrombacktrackingneedlessly.

The"inthepatternbelowmatchesthefirstcharacterofthestring,then.*matchesQuote“.Thiscausestheoverallmatchtofail,sothetextmatchedby.*isbacktrackedbyoneposition,whichleavesthefinalcharacterofthestringavailabletomatch"

/".*"/.match('"Quote"')#=>#<MatchData"\"Quote\"">

Page 682: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

If.*isgroupedatomically,itrefusestobacktrackQuote“,eventhoughthismeansthattheoverallmatchfails

/"(?>.*)"/.match('"Quote"')#=>nil

Page 683: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SubexpressionCalls

The\g<name>syntaxmatchestheprevioussubexpressionnamedname,whichcanbeagroupnameornumber,again.Thisdiffersfrombackreferencesinthatitre-executesthegroupratherthansimplytryingtore-matchthesametext.

Thispatternmatchesa(characterandassignsittotheparengroup,triestocallthattheparensub-expressionagainbutfails,thenmatchesaliteral):

/\A(?<paren>\(\g<paren>*\))*\z/=~'()'

/\A(?<paren>\(\g<paren>*\))*\z/=~'(())'#=>0

#^1

#^2

#^3

#^4

#^5

#^6

#^7

#^8

#^9

#^10

1. Matchesatthebeginningofthestring,i.e.beforethefirstcharacter.

2. Entersanamedcapturegroupcalledparen3. Matchesaliteral(,thefirstcharacterinthe

string

Page 684: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

4. Callstheparengroupagain,i.e.recursesbacktothesecondstep

5. Re-enterstheparengroup6. Matchesaliteral(,thesecondcharacterinthe

string7. Trytocallparenathirdtime,butfailbecause

doingsowouldpreventanoverallsuccessfulmatch

8. Matchaliteral),thethirdcharacterinthestring.Markstheendofthesecondrecursivecall

9. Matchaliteral),thefourthcharacterinthestring

10. Matchtheendofthestring

Page 685: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Alternation

Theverticalbarmetacharacter(|)combinestwoexpressionsintoasingleonethatmatcheseitheroftheexpressions.Eachexpressionisanalternative.

/\w(and|or)\w/.match("Feliformia")#=>#<MatchData"form"1:"or">

/\w(and|or)\w/.match("furandi")#=>#<MatchData"randi"1:"and">

/\w(and|or)\w/.match("dissemblance")#=>nil

Page 686: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CharacterProperties

The\p{}constructmatchescharacterswiththenamedproperty,muchlikePOSIXbracketclasses.

/\p{Alnum}/-Alphabeticandnumericcharacter/\p{Alpha}/-Alphabeticcharacter/\p{Blank}/-Spaceortab/\p{Cntrl}/-Controlcharacter/\p{Digit}/-Digit/\p{Graph}/-Non-blankcharacter(excludesspaces,controlcharacters,andsimilar)/\p{Lower}/-Lowercasealphabeticalcharacter/\p{Print}/-Like\p{Graph},butincludesthespacecharacter/\p{Punct}/-Punctuationcharacter/\p{Space}/-Whitespacecharacter([:blank:],newline,carriagereturn,etc.)/\p{Upper}/-Uppercasealphabetical/\p{XDigit}/-Digitallowedinahexadecimalnumber(i.e.,0-9a-fA-F)/\p{Word}/-AmemberofoneofthefollowingUnicodegeneralcategoryLetter,Mark,Number,Connector_Punctuation

Page 687: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

/\p{ASCII}/-AcharacterintheASCIIcharacterset/\p{Any}/-AnyUnicodecharacter(includingunassignedcharacters)/\p{Assigned}/-Anassignedcharacter

AUnicodecharacter'sGeneralCategoryvaluecanalsobematchedwith\p{Ab}whereAbisthecategory'sabbreviationasdescribedbelow:

/\p{L}/-'Letter'/\p{Ll}/-'Letter:Lowercase'/\p{Lm}/-'Letter:Mark'/\p{Lo}/-'Letter:Other'/\p{Lt}/-'Letter:Titlecase'/\p{Lu}/-'Letter:Uppercase/\p{Lo}/-'Letter:Other'/\p{M}/-'Mark'/\p{Mn}/-'Mark:Nonspacing'/\p{Mc}/-'Mark:SpacingCombining'/\p{Me}/-'Mark:Enclosing'/\p{N}/-'Number'/\p{Nd}/-'Number:DecimalDigit'/\p{Nl}/-'Number:Letter'/\p{No}/-'Number:Other'/\p{P}/-'Punctuation'/\p{Pc}/-'Punctuation:Connector'

Page 688: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

/\p{Pd}/-'Punctuation:Dash'/\p{Ps}/-'Punctuation:Open'/\p{Pe}/-'Punctuation:Close'/\p{Pi}/-'Punctuation:InitialQuote'/\p{Pf}/-'Punctuation:FinalQuote'/\p{Po}/-'Punctuation:Other'/\p{S}/-'Symbol'/\p{Sm}/-'Symbol:Math'/\p{Sc}/-'Symbol:Currency'/\p{Sc}/-'Symbol:Currency'/\p{Sk}/-'Symbol:Modifier'/\p{So}/-'Symbol:Other'/\p{Z}/-'Separator'/\p{Zs}/-'Separator:Space'/\p{Zl}/-'Separator:Line'/\p{Zp}/-'Separator:Paragraph'/\p{C}/-'Other'/\p{Cc}/-'Other:Control'/\p{Cf}/-'Other:Format'/\p{Cn}/-'Other:NotAssigned'/\p{Co}/-'Other:PrivateUse'/\p{Cs}/-'Other:Surrogate'

Lastly,\p{}matchesacharacter'sUnicodescript.Thefollowingscriptsaresupported:Arabic,Armenian,Balinese,Bengali,Bopomofo,Braille,Buginese,Buhid,Canadian_Aboriginal,

Page 689: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Carian,Cham,Cherokee,Common,Coptic,Cuneiform,Cypriot,Cyrillic,Deseret,Devanagari,Ethiopic,Georgian,Glagolitic,Gothic,Greek,Gujarati,Gurmukhi,Han,Hangul,Hanunoo,Hebrew,Hiragana,Inherited,Kannada,Katakana,Kayah_Li,Kharoshthi,Khmer,Lao,Latin,Lepcha,Limbu,Linear_B,Lycian,Lydian,Malayalam,Mongolian,Myanmar,New_Tai_Lue,Nko,Ogham,Ol_Chiki,Old_Italic,Old_Persian,Oriya,Osmanya,Phags_Pa,Phoenician,Rejang,Runic,Saurashtra,Shavian,Sinhala,Sundanese,Syloti_Nagri,Syriac,Tagalog,Tagbanwa,Tai_Le,Tamil,Telugu,Thaana,Thai,Tibetan,Tifinagh,Ugaritic,Vai,andYi.

UnicodecodepointU+06E9isnamed“ARABICPLACEOFSAJDAH”andbelongstotheArabicscript:

/\p{Arabic}/.match("\u06E9")#=>#<MatchData"\u06E9">

Allcharacterpropertiescanbeinvertedbyprefixingtheirnamewithacaret(^).

Letter'A'isnotintheUnicodeLl(Letter;Lowercase)category,sothismatchsucceeds:

/\p{^Ll}/.match("A")#=>#<MatchData"A">

Page 690: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Anchors

Anchorsaremetacharacterthatmatchthezero-widthpositionsbetweencharacters,anchoringthematchtoaspecificposition.

^-Matchesbeginningofline$-Matchesendofline\A-Matchesbeginningofstring.\Z-Matchesendofstring.Ifstringendswithanewline,itmatchesjustbeforenewline\z-Matchesendofstring\G-Matchespointwherelastmatchfinished\b-Matcheswordboundarieswhenoutsidebrackets;backspace(0x08)wheninsidebrackets\B-Matchesnon-wordboundaries(?=pat)-Positivelookaheadassertion:ensuresthatthefollowingcharactersmatchpat,butdoesn'tincludethosecharactersinthematchedtext(?!pat)-Negativelookaheadassertion:ensuresthatthefollowingcharactersdonotmatchpat,butdoesn'tincludethosecharactersinthematchedtext(?<=pat)-Positivelookbehindassertion:ensuresthattheprecedingcharactersmatch

Page 691: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

pat,butdoesn'tincludethosecharactersinthematchedtext(?<!pat)-Negativelookbehindassertion:ensuresthattheprecedingcharactersdonotmatchpat,butdoesn'tincludethosecharactersinthematchedtext

Ifapatternisn'tanchoreditcanbeginatanypointinthestring:

/real/.match("surrealist")#=>#<MatchData"real">

Anchoringthepatterntothebeginningofthestringforcesthematchtostartthere.'real'doesn'toccuratthebeginningofthestring,sonowthematchfails:

/\Areal/.match("surrealist")#=>nil

Thematchbelowfailsbecausealthough'Demand'contains'and',thepatterndoesnotoccuratawordboundary.

/\band/.match("Demand")

Whereasinthefollowingexample'and'hasbeenanchoredtoanon-wordboundarysoinsteadofmatchingthefirst'and'itmatchesfromthefourthletterof'demand'instead:

/\Band.+/.match("Supplyanddemandcurve")#=>#<MatchData"andcurve">

Page 692: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thepatternbelowusespositivelookaheadandpositivelookbehindtomatchtextappearingintagswithoutincludingthetagsinthematch:

/(?<=<b>)\w+(?=<\/b>)/.match("Fortunefavoursthe<b>bold</b>"

#=>#<MatchData"bold">

Page 693: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Options

Theenddelimiterforaregexpcanbefollowedbyoneormoresingle-letteroptionswhichcontrolhowthepatterncanmatch.

/pat/i-Ignorecase/pat/m-Treatanewlineasacharactermatchedby./pat/x-Ignorewhitespaceandcommentsinthepattern/pat/o-Perform#{}interpolationonlyonce

i,m,andxcanalsobeappliedonthesubexpressionlevelwiththe(?on-off)construct,whichenablesoptionson,anddisablesoptionsofffortheexpressionenclosedbytheparentheses.

/a(?i:b)c/.match('aBc')#=>#<MatchData"aBc">

/a(?i:b)c/.match('abc')#=>#<MatchData"abc">

OptionsmayalsobeusedwithRegexp.new:

Regexp.new("abc",Regexp::IGNORECASE)

Regexp.new("abc",Regexp::MULTILINE)

Regexp.new("abc#Comment",Regexp::EXTENDED)

Regexp.new("abc",Regexp::IGNORECASE|Regexp::MULTILINE

Page 694: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Free-SpacingModeandComments

Asmentionedabove,thexoptionenablesfree-spacingmode.Literalwhitespaceinsidethepatternisignored,andtheoctothorpe(#)characterintroducesacommentuntiltheendoftheline.Thisallowsthecomponentsofthepatterntobeorganizedinapotentiallymorereadablefashion.

Acontrivedpatterntomatchanumberwithoptionaldecimalplaces:

float_pat=/\A

[[:digit:]]+#1ormoredigitsbeforethedecimalpoint

(\.#Decimalpoint

[[:digit:]]+#1ormoredigitsafterthedecimalpoint

)?#Thedecimalpointandfollowingdigitsareoptional

\Z/

float_pat.match('3.14')#=>#<MatchData"3.14"1:".14">

Thereareanumberofstrategiesformatchingwhitespace:

Useapatternsuchas\sor\p{Space}.Useescapedwhitespacesuchas\,i.e.aspaceprecededbyabackslash.Useacharacterclasssuchas[].

Commentscanbeincludedinanon-xpatternwiththe(?#comment)construct,where

Page 695: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

commentisarbitrarytextignoredbytheregexpengine.

Page 696: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Encoding

Regularexpressionsareassumedtousethesourceencoding.Thiscanbeoverriddenwithoneofthefollowingmodifiers.

/pat/u-UTF-8/pat/e-EUC-JP/pat/s-Windows-31J/pat/n-ASCII-8BIT

Aregexpcanbematchedagainstastringwhentheyeithershareanencoding,ortheregexp'sencodingisUS-ASCIIandthestring'sencodingisASCII-compatible.

IfamatchbetweenincompatibleencodingsisattemptedanEncoding::CompatibilityErrorexceptionisraised.

TheRegexp#fixed_encoding?predicateindicateswhethertheregexphasafixedencoding,thatisoneincompatiblewithASCII.Aregexp'sencodingcanbeexplicitlyfixedbysupplyingRegexp::FIXEDENCODINGasthesecondargumentofRegexp.new:

r=Regexp.new("a".force_encoding("iso-8859-1"),Regexp

r=~"a\u3042"

#=>Encoding::CompatibilityError:incompatibleencodingregexpmatch

(ISO-8859-1regexpwithUTF-8string)

Page 697: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference
Page 698: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Specialglobalvariables

Patternmatchingsetssomeglobalvariables:

$~isequivalentto::last_match;$&containsthecompletematchedtext;$`containsstringbeforematch;$'containsstringaftermatch;$1,$2andsooncontaintextmatchingfirst,second,etccapturegroup;$+containslastcapturegroup.

Example:

m=/s(\w{2}).*(c)/.match('haystack')#=>#<MatchData"stac"1:"ta"2:"c">

$~#=>#<MatchData"stac"1:"ta"2:"c">

Regexp.last_match#=>#<MatchData"stac"1:"ta"2:"c">

$&#=>"stac"

#sameasm[0]

$`#=>"hay"

#sameasm.pre_match

$'#=>"k"

#sameasm.post_match

$1#=>"ta"

#sameasm[1]

$2#=>"c"

#sameasm[2]

$3#=>nil

#nothirdgroupinpattern

$+#=>"c"

#sameasm[-1]

Page 699: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Theseglobalvariablesarethread-localandmethod-localvariables.

Page 700: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Performance

Certainpathologicalcombinationsofconstructscanleadtoabysmallybadperformance.

Considerastringof25as,ad,4as,andac.

s='a'*25+'d'+'a'*4+'c'

#=>"aaaaaaaaaaaaaaaaaaaaaaaaadaaaac"

Thefollowingpatternsmatchinstantlyasyouwouldexpect:

/(b|a)/=~s#=>0

/(b|a+)/=~s#=>0

/(b|a+)*/=~s#=>0

However,thefollowingpatterntakesappreciablylonger:

/(b|a+)*c/=~s#=>26

Thishappensbecauseanatomintheregexpisquantifiedbybothanimmediate+andanenclosing*withnothingtodifferentiatewhichisincontrolofanyparticularcharacter.Thenondeterminismthatresultsproducessuper-linearperformance.(ConsultMasteringRegularExpressions(3rded.),pp222,byJefferyFriedl,foranin-depthanalysis).Thisparticularcasecanbefixedbyuseofatomicgrouping,which

Page 701: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

preventstheunnecessarybacktracking:

(start=Time.now)&&/(b|a+)*c/=~s&&(Time.now

#=>24.702736882

(start=Time.now)&&/(?>b|a+)*c/=~s&&(Time.

#=>0.000166571

Asimilarcaseistypifiedbythefollowingexample,whichtakesapproximately60secondstoexecuteforme:

Matchastringof29asagainstapatternof29optionalasfollowedby29mandatoryas:

Regexp.new('a?'*29+'a'*29)=~'a'*29

The29optionalasmatchthestring,butthispreventsthe29mandatoryasthatfollowfrommatching.Rubymustthenbacktrackrepeatedlysoastosatisfyasmanyoftheoptionalmatchesasitcanwhilestillmatchingthemandatory29.Itisplaintousthatnoneoftheoptionalmatchescansucceed,butthisfactunfortunatelyeludesRuby.

Thebestwaytoimproveperformanceistosignificantlyreducetheamountofbacktrackingneeded.Forthiscase,insteadofindividuallymatching29optionalas,arangeofoptionalascanbematchedallatoncewitha{0,29}:

Regexp.new('a{0,29}'+'a'*29)=~'a'*29

Page 702: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

InFilesre.c

ParentObject

Constants

EXTENDED

see#optionsand::new

FIXEDENCODING

see#optionsand::new

IGNORECASE

see#optionsand::new

MULTILINE

see#optionsand::new

NOENCODING

see#optionsand::new

PublicClassMethods

SynonymforRegexp.newcompile(*args)

Page 703: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Escapesanycharactersthatwouldhavespecialmeaninginaregularexpression.Returnsanewescapedstring,orselfifnocharactersareescaped.Foranystring,Regexp.new(Regexp.escape(str))=~strwillbetrue.

Regexp.escape('\*?{}.')#=>\\\*\?\{\}\.

ThefirstformreturnstheMatchDataobjectgeneratedbythelastsuccessfulpatternmatch.Equivalenttoreadingthespecialglobalvariable$~(seeSpecialglobalvariablesinRegexpfordetails).

ThesecondformreturnsthenthfieldinthisMatchDataobject.ncanbeastringorsymboltoreferenceanamedcapture.

Notethatthe::last_matchislocaltothethreadandmethodscopeofthemethodthatdidthepatternmatch.

/c(.)t/=~'cat'#=>0

Regexp.last_match#=>#<MatchData"cat"1:"a">

Regexp.last_match(0)#=>"cat"

Regexp.last_match(1)#=>"a"

Regexp.last_match(2)#=>nil

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/=~"var=val"

Regexp.last_match#=>#<MatchData"var=val"lhs:"var"rhs:"val">

Regexp.last_match(:lhs)#=>"var"

Regexp.last_match(:rhs)#=>"val"

escape(str)→stringquote(str)→string

last_match→matchdatalast_match(n)→str

new(string,[options[,kcode]])→regexp

Page 704: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Constructsanewregularexpressionfrompattern,whichcanbeeitheraStringoraRegexp(inwhichcasethatregexp'soptionsarepropagated),andnewoptionsmaynotbespecified(achangeasofRuby1.8).

IfoptionsisaFixnum,itshouldbeoneormoreoftheconstantsRegexp::EXTENDED,Regexp::IGNORECASE,andRegexp::MULTILINE,or-edtogether.Otherwise,ifoptionsisnotnilorfalse,theregexpwillbecaseinsensitive.

Whenthekcodeparameteris`n'or`N'setstheregexpnoencoding.Itmeansthattheregexpisforbinarystrings.

r1=Regexp.new('^a-z+:\s+\w+')#=>/^a-z+:\s+\w+/

r2=Regexp.new('cat',true)#=>/cat/i

r3=Regexp.new(r2)#=>/cat/i

r4=Regexp.new('dog',Regexp::EXTENDED|Regexp::IGNORECASE

Escapesanycharactersthatwouldhavespecialmeaninginaregularexpression.Returnsanewescapedstring,orselfifnocharactersareescaped.Foranystring,Regexp.new(Regexp.escape(str))=~strwillbetrue.

Regexp.escape('\*?{}.')#=>\\\*\?\{\}\.

new(regexp)→regexpcompile(string,[options[,kcode]])→regexpcompile(regexp)→regexp

escape(str)→stringquote(str)→string

try_convert(obj)→reornil

Page 705: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

TrytoconvertobjintoaRegexp,usingto_regexpmethod.Returnsconvertedregexpornilifobjcannotbeconvertedforanyreason.

Regexp.try_convert(/re/)#=>/re/

Regexp.try_convert("re")#=>nil

o=Object.new

Regexp.try_convert(o)#=>nil

defo.to_regexp()/foo/end

Regexp.try_convert(o)#=>/foo/

ReturnaRegexpobjectthatistheunionofthegivenpatterns,i.e.,willmatchanyofitsparts.ThepatternscanbeRegexpobjects,inwhichcasetheiroptionswillbepreserved,orStrings.Ifnopatternsaregiven,returns/(?!)/.Thebehaviorisunspecifiedifanygivenpatterncontainscapture.

Regexp.union#=>/(?!)/

Regexp.union("penzance")#=>/penzance/

Regexp.union("a+b*c")#=>/a\+b\*c/

Regexp.union("skiing","sledding")#=>/skiing|sledding/

Regexp.union(["skiing","sledding"])#=>/skiing|sledding/

Regexp.union(/dogs/,/cats/)#=>/(?-mix:dogs)|(?i-mx:cats)/

Note:theargumentsfor::unionwilltrytobeconvertedintoaregularexpressionliteralviato_regexp.

PublicInstanceMethods

union(pat1,pat2,...)→new_regexpunion(pats_ary)→new_regexp

rxp==other_rxp→trueorfalseeql?(other_rxp)→trueorfalse

Page 706: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Equality—Tworegexpsareequaliftheirpatternsareidentical,theyhavethesamecharactersetcode,andtheircasefold?valuesarethesame.

/abc/==/abc/#=>false

/abc/==/abc/#=>false

/abc/==/abc/#=>false

/abc/==/abc/#=>false

CaseEquality—Usedincasestatements.

a="HELLO"

casea

when/^[a-z]*$/;print"Lowercase\n"

when/^[A-Z]*$/;print"Uppercase\n"

else;print"Mixedcase\n"

end

#=>"Uppercase"

Followingaregularexpressionliteralwiththe#===operatorallowsyoutocompareagainstaString.

/^[a-z]*$/==="HELLO"#=>false

/^[A-Z]*$/==="HELLO"#=>true

Match—Matchesrxpagainststr.

/at/=~"inputdata"#=>7

/ax/=~"inputdata"#=>nil

If=~isusedwitharegexpliteralwithnamedcaptures,capturedstrings(ornil)isassignedtolocalvariablesnamedbythecapturenames.

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/=~"x=y"

plhs#=>"x"

prhs#=>"y"

rxp===str→trueorfalse

rxp=~str→integerornil

Page 707: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ifitisnotmatched,nilisassignedforthevariables.

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/=~"x="

plhs#=>nil

prhs#=>nil

ThisassignmentisimplementedintheRubyparser.Theparserdetects'regexp-literal=~expression'fortheassignment.Theregexpmustbealiteralwithoutinterpolationandplacedatlefthandside.

Theassignmentdoesnotoccuriftheregexpisnotaliteral.

re=/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/

re=~"x=y"

plhs#undefinedlocalvariable

prhs#undefinedlocalvariable

Aregexpinterpolation,#{},alsodisablestheassignment.

rhs_pat=/(?<rhs>\w+)/

/(?<lhs>\w+)\s*=\s*#{rhs_pat}/=~"x=y"

plhs#undefinedlocalvariable

Theassignmentdoesnotoccuriftheregexpisplacedattherighthandside.

"x=y"=~/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/

plhs,rhs#undefinedlocalvariable

Returnsthevalueofthecase-insensitiveflag.

/a/.casefold?#=>false

/a/.casefold?#=>true

/(?i:a)/.casefold?#=>false

casefold?→trueorfalse

encoding→encoding

Page 708: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstheEncodingobjectthatrepresentstheencodingofobj.

Equality—Tworegexpsareequaliftheirpatternsareidentical,theyhavethesamecharactersetcode,andtheircasefold?valuesarethesame.

/abc/==/abc/#=>false

/abc/==/abc/#=>false

/abc/==/abc/#=>false

/abc/==/abc/#=>false

ReturnsfalseifrxpisapplicabletoastringwithanyASCIIcompatibleencoding.Returnstrueotherwise.

r=/a/

r.fixed_encoding?#=>false

r=~"\u{6666}a"#=>2

r=~"\xa1\xa2a".force_encoding("euc-jp")#=>2

r=~"abc".force_encoding("euc-jp")#=>0

r=/a/

r.fixed_encoding?#=>true

r.encoding#=>#<Encoding:UTF-8>

r=~"\u{6666}a"#=>2

r=~"\xa1\xa2".force_encoding("euc-jp")#=>ArgumentError

r=~"abc".force_encoding("euc-jp")#=>0

r=/\u{6666}/

r.fixed_encoding?#=>true

r.encoding#=>#<Encoding:UTF-8>

r=~"\u{6666}a"#=>0

r=~"\xa1\xa2".force_encoding("euc-jp")#=>ArgumentError

r=~"abc".force_encoding("euc-jp")#=>nil

rxp==other_rxp→trueorfalseeql?(other_rxp)→trueorfalse

fixed_encoding?→trueorfalse

Page 709: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Produceahashbasedonthetextandoptionsofthisregularexpression.

SeealsoObject#hash.

Produceanicelyformattedstring-versionofrxp.Perhapssurprisingly,#inspectactuallyproducesthemorenaturalversionofthestringthan#to_s.

/ab+c/x.inspect#=>"/ab+c/ix"

ReturnsaMatchDataobjectdescribingthematch,orniliftherewasnomatch.Thisisequivalenttoretrievingthevalueofthespecialvariable$~followinganormalmatch.Ifthesecondparameterispresent,itspecifiesthepositioninthestringtobeginthesearch.

/(.)(.)(.)/.match("abc")[2]#=>"b"

/(.)(.)/.match("abc",1)[2]#=>"c"

Ifablockisgiven,invoketheblockwithMatchDataifmatchsucceed,sothatyoucanwrite

pat.match(str){|m|...}

insteadof

ifm=pat.match(str)

...

end

Thereturnvalueisavaluefromblockexecutionin

hash→fixnum

inspect→string

match(str)→matchdataornilmatch(str,pos)→matchdataornil

Page 710: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

thiscase.

Returnsahashrepresentinginformationaboutnamedcapturesofrxp.

Akeyofthehashisanameofthenamedcaptures.Avalueofthehashisanarraywhichislistofindexesofcorrespondingnamedcaptures.

/(?<foo>.)(?<bar>.)/.named_captures

#=>{"foo"=>[1],"bar"=>[2]}

/(?<foo>.)(?<foo>.)/.named_captures

#=>{"foo"=>[1,2]}

Iftherearenonamedcaptures,anemptyhashisreturned.

/(.)(.)/.named_captures

#=>{}

Returnsalistofnamesofcapturesasanarrayofstrings.

/(?<foo>.)(?<bar>.)(?<baz>.)/.names

#=>["foo","bar","baz"]

/(?<foo>.)(?<foo>.)/.names

#=>["foo"]

/(.)(.)/.names

#=>[]

ReturnsthesetofbitscorrespondingtotheoptionsusedwhencreatingthisRegexp(seeRegexp::newfor

named_captures→hash

names→[name1,name2,...]

options→fixnum

Page 711: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

details.Notethatadditionalbitsmaybesetinthereturnedoptions:theseareusedinternallybytheregularexpressioncode.TheseextrabitsareignorediftheoptionsarepassedtoRegexp::new.

Regexp::IGNORECASE#=>1

Regexp::EXTENDED#=>2

Regexp::MULTILINE#=>4

/cat/.options#=>0

/cat/x.options#=>3

Regexp.new('cat',true).options#=>1

/\xa1\xa2/.options#=>16

r=/cat/x

Regexp.new(r.source,r.options)#=>/cat/ix

Returnstheoriginalstringofthepattern.

/ab+c/x.source#=>"ab+c"

Notethatescapesequencesareretainedasis.

/\x20\+/.source#=>"\\x20\\+"

Returnsastringcontainingtheregularexpressionanditsoptions(usingthe(?opts:source)notation.ThisstringcanbefedbackintoRegexp::newtoaregularexpressionwiththesamesemanticsastheoriginal.(However,Regexp#==maynotreturntruewhencomparingthetwo,asthesourceoftheregularexpressionitselfmaydiffer,astheexampleshows).Regexp#inspectproducesagenerallymorereadableversionofrxp.

r1=/ab+c/x#=>/ab+c/ix

source→str

to_s→str

Page 712: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

s1=r1.to_s#=>"(?ix-m:ab+c)"

r2=Regexp.new(s1)#=>/(?ix-m:ab+c)/

r1==r2#=>false

r1.source#=>"ab+c"

r2.source#=>"(?ix-m:ab+c)"

Match—Matchesrxpagainstthecontentsof$_.Equivalenttorxp=~$_.

$_="inputdata"

~/at/#=>7

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

~rxp→integerornil

Page 713: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRegexpErrorRaisedwhengivenaninvalidregexpexpression.

Regexp.new("?")

raisestheexception:

RegexpError:targetofrepeatoperatorisnotspecified:/?/

InFilesre.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 714: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRipper

InFilesparse.c

ParentObject

Constants

Version

versionofRipper

PublicClassMethods

CreateanewRipperobject.srcmustbeaString,anIO,oranObjectwhichhasgetsmethod.

Thismethoddoesnotstartsparsing.Seealso#parseand#parse.

PublicInstanceMethods

new(src,filename="(ripper)",lineno=1)→ripper

Page 715: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returncolumnnumberofcurrentparsingline.Thisnumberstartsfrom0.

Returnencodingofthesource.

Returntrueifparsedsourceendedby+__END__+.

Returntrueifparsedsourcehaserrors.

Returncurrentparsingfilename.

Returnlinenumberofcurrentparsingline.Thisnumberstartsfrom1.

Startparsingandreturnsthevalueoftherootaction.

Getyydebug.

Setyydebug.

ripper#column→Integer

ripper#encoding→encoding

ripper#end_seen?→Boolean

ripper#error?→Boolean

ripper#filename→String

ripper#lineno→Integer

ripper#parse

yydebug→trueorfalse

yydebug=flag

Page 716: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 717: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRubyVM::RubyVM

InFilesiseq.cvm.c

ParentObject

Constants

DEFAULT_PARAMS

DEFAULT_PARAMSThisconstantvariableshowsVM'sdefaultparameters.NotethatchangingthesevaluesdoesnotaffectVMexecution.Specificationisnotstableandyoushouldnotdependonthisvalue.Ofcourse,thisconstantisMRIspecific.

INSTRUCTION_NAMES

INSTRUCTION_NAMES

OPTS

OPTS,whichshowsvmbuildoptions

Page 718: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PublicClassMethods

ReturnsaHashcontainingimplementation-dependentcountersinsidetheVM.

Thishashincludesinformationaboutmethod/constantcacheserials:

{

:global_method_state=>251,

:global_constant_state=>481,

:class_serial=>9029

}

Thecontentsofthehashareimplementationspecificandmaybechangedinthefuture.

ThismethodisonlyexpectedtoworkonCRuby.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

stat→Hashstat(hsh)→hshstat(Symbol)→Numeric

Page 719: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRubyVM::Env::RubyVM::Env

InFilesiseq.c

ParentObject

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 720: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRubyVM::InstructionSequenceTheInstructionSequenceclassrepresentsacompiledsequenceofinstructionsfortheRubyVirtualMachine.

Withit,youcangetahandletotheinstructionsthatmakeupamethodoraproc,compilestringsofRubycodedowntoVMinstructions,anddisassembleinstructionsequencestostringsforeasyinspection.ItismostlyusefulifyouwanttolearnhowtheRubyVMworks,butitalsoletsyoucontrolvarioussettingsfortheRubyiseqcompiler.

YoucanfindthesourcefortheVMinstructionsininsns.defintheRubysource.

TheinstructionsequenceresultswillalmostcertainlychangeasRubychanges,soexampleoutputinthisdocumentationmaybedifferentfromwhatyousee.

InFilesiseq.c

Parent

Page 721: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Object

PublicClassMethods

Takessource,aStringofRubycodeandcompilesittoanInstructionSequence.

Optionallytakesfile,path,andlinewhichdescribethefilename,absolutepathandfirstlinenumberoftherubycodeinsourcewhicharemetadataattachedtothereturnediseq.

options,whichcanbetrue,falseoraHash,isusedtomodifythedefaultbehavioroftheRubyiseqcompiler.

Fordetailsregardingvalidcompileoptionssee::compile_option=.

RubyVM::InstructionSequence.compile("a=1+2")

#=><RubyVM::InstructionSequence:<compiled>@<compiled>>

Takesfile,aStringwiththelocationofaRubysourcefile,reads,parsesandcompilesthefile,andreturnsiseq,thecompiledInstructionSequencewithsourcelocationmetadataset.

Optionallytakesoptions,whichcanbetrue,falseoraHash,tomodifythedefaultbehavioroftheRubyiseqcompiler.

compile(source[,file[,path[,line[,options]]]])→iseqnew(source[,file[,path[,line[,options]]]])→iseq

compile_file(file[,options])→iseq

Page 722: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Fordetailsregardingvalidcompileoptionssee::compile_option=.

#/tmp/hello.rb

puts"Hello,world!"

#elsewhere

RubyVM::InstructionSequence.compile_file("/tmp/hello.rb"

#=><RubyVM::InstructionSequence:<main>@/tmp/hello.rb>

ReturnsahashofdefaultoptionsusedbytheRubyiseqcompiler.

Fordetails,see::compile_option=.

SetsthedefaultvaluesforvariousoptimizationsintheRubyiseqcompiler.

Possiblevaluesforoptionsincludetrue,whichenablesalloptions,falsewhichdisablesalloptions,andnilwhichleavesalloptionsunchanged.

YoucanalsopassaHashofoptionsthatyouwanttochange,anyoptionsnotpresentinthehashwillbeleftunchanged.

Possibleoptionnames(whicharekeysinoptions)whichcanbesettotrueorfalseinclude:

:inline_const_cache

:instructions_unification

:operands_unification

:peephole_optimization

:specialized_instruction

compile_option→options

compile_option=options

Page 723: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

:stack_caching

:tailcall_optimization

:trace_instruction

Additionally,:debug_levelcanbesettoaninteger.

Thesedefaultoptionscanbeoverwrittenforasinglerunoftheiseqcompilerbypassinganyoftheabovevaluesastheoptionsparameterto::new,::compileand::compile_file.

Takesbody,aMethodorProcobject,andreturnsaStringwiththehumanreadableinstructionsforbody.

ForaMethodobject:

#/tmp/method.rb

defhello

puts"hello,world"

end

putsRubyVM::InstructionSequence.disasm(method(:hello))

Produces:

==disasm:<RubyVM::InstructionSequence:hello@/tmp/method.rb>============

0000trace8(1)

0002trace1(2)

0004putself

0005putstring"hello,world"

0007send:puts,1,nil,8,<ic:0>

0013trace16(3)

0015leave(2)

ForaProc:

#/tmp/proc.rb

p=proc{num=1+2}

disasm(body)→strdisassemble(body)→str

Page 724: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

putsRubyVM::InstructionSequence.disasm(p)

Produces:

==disasm:<RubyVM::InstructionSequence:blockin<main>@/tmp/proc.rb>===

==catchtable

|catchtype:redost:0000ed:0012sp:0000cont:0000

|catchtype:nextst:0000ed:0012sp:0000cont:0012

|------------------------------------------------------------------------

localtable(size:2,argc:0[opts:0,rest:-1,post:0,block:-1]s1)

[2]num

0000trace1(1)

0002putobject1

0004putobject2

0006opt_plus<ic:1>

0008dup

0009setlocalnum,0

0012leave

Takesbody,aMethodorProcobject,andreturnsaStringwiththehumanreadableinstructionsforbody.

ForaMethodobject:

#/tmp/method.rb

defhello

puts"hello,world"

end

putsRubyVM::InstructionSequence.disasm(method(:hello))

Produces:

==disasm:<RubyVM::InstructionSequence:hello@/tmp/method.rb>============

0000trace8(1)

0002trace1(2)

0004putself

0005putstring"hello,world"

0007send:puts,1,nil,8,<ic:0>

0013trace16(3)

disasm(body)→strdisassemble(body)→str

Page 725: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

0015leave(2)

ForaProc:

#/tmp/proc.rb

p=proc{num=1+2}

putsRubyVM::InstructionSequence.disasm(p)

Produces:

==disasm:<RubyVM::InstructionSequence:blockin<main>@/tmp/proc.rb>===

==catchtable

|catchtype:redost:0000ed:0012sp:0000cont:0000

|catchtype:nextst:0000ed:0012sp:0000cont:0012

|------------------------------------------------------------------------

localtable(size:2,argc:0[opts:0,rest:-1,post:0,block:-1]s1)

[2]num

0000trace1(1)

0002putobject1

0004putobject2

0006opt_plus<ic:1>

0008dup

0009setlocalnum,0

0012leave

Takessource,aStringofRubycodeandcompilesittoanInstructionSequence.

Optionallytakesfile,path,andlinewhichdescribethefilename,absolutepathandfirstlinenumberoftherubycodeinsourcewhicharemetadataattachedtothereturnediseq.

options,whichcanbetrue,falseoraHash,isusedtomodifythedefaultbehavioroftheRubyiseq

compile(source[,file[,path[,line[,options]]]])→iseqnew(source[,file[,path[,line[,options]]]])→iseq

Page 726: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

compiler.

Fordetailsregardingvalidcompileoptionssee::compile_option=.

RubyVM::InstructionSequence.compile("a=1+2")

#=><RubyVM::InstructionSequence:<compiled>@<compiled>>

Returnstheinstructionsequencecontainingthegivenprocormethod.

Forexample,usingirb:

#aproc

>p=proc{num=1+2}

>RubyVM::InstructionSequence.of(p)

>#=><RubyVM::InstructionSequence:blockinirb_binding@(irb)>

#foramethod

>deffoo(bar);putsbar;end

>RubyVM::InstructionSequence.of(method(:foo))

>#=><RubyVM::InstructionSequence:foo@(irb)>

Using::compile_file:

#/tmp/iseq_of.rb

defhello

puts"hello,world"

end

$a_global_proc=proc{str='a'+'b'}

#inirb

>require'/tmp/iseq_of.rb'

#firstthemethodhello

>RubyVM::InstructionSequence.of(method(:hello))

>#=>#<RubyVM::InstructionSequence:0x007fb73d7cb1d0>

#thentheglobalproc

>RubyVM::InstructionSequence.of($a_global_proc)

of(p1)

Page 727: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

>#=>#<RubyVM::InstructionSequence:0x007fb73d7caf78>

PublicInstanceMethods

Returnstheabsolutepathofthisinstructionsequence.

niliftheiseqwasevaluatedfromastring.

Forexample,using::compile_file:

#/tmp/method.rb

defhello

puts"hello,world"

end

#inirb

>iseq=RubyVM::InstructionSequence.compile_file('/tmp/method.rb'

>iseq.absolute_path#=>/tmp/method.rb

Returnsthebaselabelofthisinstructionsequence.

Forexample,usingirb:

iseq=RubyVM::InstructionSequence.compile('num=1+2'

#=><RubyVM::InstructionSequence:<compiled>@<compiled>>

iseq.base_label

#=>"<compiled>"

Using::compile_file:

#/tmp/method.rb

defhello

puts"hello,world"

end

absolute_path()

base_label()

Page 728: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#inirb

>iseq=RubyVM::InstructionSequence.compile_file('/tmp/method.rb'

>iseq.base_label#=><main>

ReturnstheinstructionsequenceasaStringinhumanreadableform.

putsRubyVM::InstructionSequence.compile('1+2').disasm

Produces:

==disasm:<RubyVM::InstructionSequence:<compiled>@<compiled>>==========

0000trace1(1)

0002putobject1

0004putobject2

0006opt_plus<ic:1>

0008leave

ReturnstheinstructionsequenceasaStringinhumanreadableform.

putsRubyVM::InstructionSequence.compile('1+2').disasm

Produces:

==disasm:<RubyVM::InstructionSequence:<compiled>@<compiled>>==========

0000trace1(1)

0002putobject1

0004putobject2

0006opt_plus<ic:1>

0008leave

disasm→strdisassemble→str

disasm→strdisassemble→str

Page 729: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Evaluatestheinstructionsequenceandreturnstheresult.

RubyVM::InstructionSequence.compile("1+2").eval#=>3

Returnsthenumberofthefirstsourcelinewheretheinstructionsequencewasloadedfrom.

Forexample,usingirb:

iseq=RubyVM::InstructionSequence.compile('num=1+2'

#=><RubyVM::InstructionSequence:<compiled>@<compiled>>

iseq.first_lineno

#=>1

Returnsahuman-readablestringrepresentationofthisinstructionsequence,includingthelabelandpath.

Returnsthelabelofthisinstructionsequence.

<main>ifit'satthetoplevel,<compiled>ifitwasevaluatedfromastring.

Forexample,usingirb:

iseq=RubyVM::InstructionSequence.compile('num=1+2'

#=><RubyVM::InstructionSequence:<compiled>@<compiled>>

iseq.label

#=>"<compiled>"

eval→obj

first_lineno()

inspect()

label()

Page 730: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Using::compile_file:

#/tmp/method.rb

defhello

puts"hello,world"

end

#inirb

>iseq=RubyVM::InstructionSequence.compile_file('/tmp/method.rb'

>iseq.label#=><main>

ExperimentalMRIspecificfeature,onlyavailableasClevelapi.Returnsallspecified_lineevents.

ExperimentalMRIspecificfeature,onlyavailableasClevelapi.Setaspecified_lineeventatthegivenlineposition,ifthesetparameteristrue.

Thismethodisusefulforbuildingadebuggerbreakpointataspecificline.

ATypeErrorisraisedifsetisnotboolean.

IfposisanegativeintegeraTypeErrorexceptionisraised.

Returnsthepathofthisinstructionsequence.

<compiled>iftheiseqwasevaluatedfromastring.

Forexample,usingirb:

line_trace_all()

line_trace_specify(p1,p2)

path()

Page 731: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

iseq=RubyVM::InstructionSequence.compile('num=1+2'

#=><RubyVM::InstructionSequence:<compiled>@<compiled>>

iseq.path

#=>"<compiled>"

Using::compile_file:

#/tmp/method.rb

defhello

puts"hello,world"

end

#inirb

>iseq=RubyVM::InstructionSequence.compile_file('/tmp/method.rb'

>iseq.path#=>/tmp/method.rb

ReturnsanArraywith14elementsrepresentingtheinstructionsequencewiththefollowingdata:

magicAstringidentifyingthedataformat.AlwaysYARVInstructionSequence/SimpleDataFormat.

major_versionThemajorversionoftheinstructionsequence.

minor_versionTheminorversionoftheinstructionsequence.

format_typeAnumberidentifyingthedataformat.Always1.

to_a→ary

Page 732: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

miscAhashcontaining:

:arg_size

thetotalnumberofargumentstakenbythemethodortheblock(0ifiseqdoesn'trepresentamethodorblock)

:local_size

thenumberoflocalvariables+1

:stack_max

usedincalculatingthestackdepthatwhichaSystemStackErroristhrown.

labelThenameofthecontext(block,method,class,module,etc.)thatthisinstructionsequencebelongsto.

<main>ifit'satthetoplevel,<compiled>ifitwasevaluatedfromastring.

pathTherelativepathtotheRubyfilewheretheinstructionsequencewasloadedfrom.

<compiled>iftheiseqwasevaluatedfromastring.

absolute_pathTheabsolutepathtotheRubyfilewheretheinstructionsequencewasloadedfrom.

niliftheiseqwasevaluatedfromastring.

Page 733: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

first_linenoThenumberofthefirstsourcelinewheretheinstructionsequencewasloadedfrom.

typeThetypeoftheinstructionsequence.

Validvaluesare:top,:method,:block,:class,:rescue,:ensure,:eval,:main,and:defined_guard.

localsAnarraycontainingthenamesofallargumentsandlocalvariablesassymbols.

paramsAnHashobjectcontainingparameterinformation.

Moreinfoaboutthesevaluescanbefoundinvm_core.h.

catch_tableAlistofexceptionsandcontrolflowoperators(rescue,next,redo,break,etc.).

bytecodeAnarrayofarrayscontainingtheinstructionnamesandoperandsthatmakeupthebodyoftheinstructionsequence.

NotethatthisformatisMRIspecificandversiondependent.

GeneratedbyRDoc3.12.2.

Page 734: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedwiththeDarkfishRdocGenerator3.

Page 735: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classRuntimeErrorAgenericerrorclassraisedwhenaninvalidoperationisattempted.

[1,2,3].freeze<<4

raisestheexception:

RuntimeError:can'tmodifyfrozenArray

Kernel#raisewillraiseaRuntimeErrorifnoExceptionclassisspecified.

raise"ouch"

raisestheexception:

RuntimeError:ouch

InFileserror.c

ParentStandardError

GeneratedbyRDoc3.12.2.

Page 736: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedwiththeDarkfishRdocGenerator3.

Page 737: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classScriptErrorScriptErroristhesuperclassforerrorsraisedwhenascriptcannotbeexecutedbecauseofaLoadError,NotImplementedErrororaSyntaxError.NotethesetypeofScriptErrorsarenotStandardErrorandwillnotberescuedunlessitisspecifiedexplicitly(oritsancestorException).

InFileserror.c

ParentException

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 738: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classSecurityErrorRaisedwhenattemptingapotentialunsafeoperation,typicallywhenthe$SAFElevelisraisedabove0.

foo="bar"

proc=Proc.newdo

$SAFE=3

foo.untaint

end

proc.call

raisestheexception:

SecurityError:Insecure:Insecureoperation`untaint'atlevel3

InFileserror.c

ParentException

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 739: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

moduleSignalManyoperatingsystemsallowsignalstobesenttorunningprocesses.Somesignalshaveadefinedeffectontheprocess,whileothersmaybetrappedatthecodelevelandactedupon.Forexample,yourprocessmaytraptheUSR1signalanduseittotoggledebugging,andmayuseTERMtoinitiateacontrolledshutdown.

pid=forkdo

Signal.trap("USR1")do

$debug=!$debug

puts"Debugnow:#$debug"

end

Signal.trap("TERM")do

puts"Terminating..."

shutdown()

end

#...dosomework...

end

Process.detach(pid)

#Controllingprogram:

Process.kill("USR1",pid)

#...

Process.kill("USR1",pid)

#...

Process.kill("TERM",pid)

produces:

Debugnow:true

Debugnow:false

Page 740: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Terminating...

Thelistofavailablesignalnamesandtheirinterpretationissystemdependent.Signaldeliverysemanticsmayalsovarybetweensystems;inparticularsignaldeliverymaynotalwaysbereliable.

InFilessignal.c

PublicClassMethods

Returnsalistofsignalnamesmappedtothecorrespondingunderlyingsignalnumbers.

Signal.list#=>{"EXIT"=>0,"HUP"=>1,"INT"=>2,"QUIT"=>3,"ILL"=>4,"TRAP"=>5,"IOT"=>6,"ABRT"=>6,"FPE"=>8,"KILL"=>9,"BUS"=>7,"SEGV"=>11,"SYS"=>31,"PIPE"=>13,"ALRM"=>14,"TERM"=>15,"URG"=>23,"STOP"=>19,"TSTP"=>20,"CONT"=>18,"CHLD"=>17,"CLD"=>17,"TTIN"=>21,"TTOU"=>22,"IO"=>29,"XCPU"=>24,"XFSZ"=>25,"VTALRM"=>26,"PROF"=>27,"WINCH"=>28,"USR1"=>10,"USR2"=>12,"PWR"=>30,"POLL"=>29}

convertsignalnumbertosignalname

Signal.trap("INT"){|signo|putsSignal.signame(signo

Process.kill("INT",0)

produces:

INT

list→a_hash

signame(signo)→string

trap(signal,command)→obj

Page 741: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Specifiesthehandlingofsignals.Thefirstparameterisasignalname(astringsuchas“SIGALRM'',“SIGUSR1'',andsoon)orasignalnumber.Thecharacters“SIG''maybeomittedfromthesignalname.Thecommandorblockspecifiescodetoberunwhenthesignalisraised.Ifthecommandisthestring“IGNORE''or“SIG_IGN'',thesignalwillbeignored.Ifthecommandis“DEFAULT''or“SIG_DFL'',theRuby'sdefaulthandlerwillbeinvoked.Ifthecommandis“EXIT'',thescriptwillbeterminatedbythesignal.Ifthecommandis“SYSTEM_DEFAULT'',theoperatingsystem'sdefaulthandlerwillbeinvoked.Otherwise,thegivencommandorblockwillberun.Thespecialsignalname“EXIT''orsignalnumberzerowillbeinvokedjustpriortoprogramtermination.trapreturnstheprevioushandlerforthegivensignal.

Signal.trap(0,proc{puts"Terminating:#{$$}"})

Signal.trap("CLD"){puts"Childdied"}

fork&&Process.wait

produces:

Terminating:27461

Childdied

Terminating:27460

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

trap(signal){||block}→obj

Page 742: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classSignalExceptionRaisedwhenasignalisreceived.

begin

Process.kill('HUP',Process.pid)

sleep#waitforreceivertohandlesignalsentbyProcess.kill

rescueSignalException=>e

puts"receivedException#{e}"

end

produces:

receivedExceptionSIGHUP

InFileserror.csignal.c

ParentException

PublicClassMethods

new(sig_name)→signal_exceptionnew(sig_number[,name])→signal_exception

Page 743: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ConstructanewSignalExceptionobject.sig_nameshouldbeaknownsignalname.

PublicInstanceMethods

Returnsasignalnumber.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

signo→num

Page 744: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classStandardErrorThemoststandarderrortypesaresubclassesofStandardError.ArescueclausewithoutanexplicitExceptionclasswillrescueallStandardErrors(andonlythose).

deffoo

raise"Oups"

end

foorescue"Hello"#=>"Hello"

Ontheotherhand:

require'does/not/exist'rescue"Hi"

raisestheexception:

LoadError:nosuchfiletoload--does/not/exist

InFileserror.c

ParentException

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 745: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classStopIterationRaisedtostoptheiteration,inparticularbyEnumerator#next.ItisrescuedbyKernel#loop.

loopdo

puts"Hello"

raiseStopIteration

puts"World"

end

puts"Done!"

produces:

Hello

Done!

InFilesenumerator.c

ParentIndexError

PublicInstanceMethods

Returnsthereturnvalueoftheiterator.

o=Object.new

result→value

Page 746: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

defo.each

yield1

yield2

yield3

100

end

e=o.to_enum

putse.next#=>1

putse.next#=>2

putse.next#=>3

begin

e.next

rescueStopIteration=>ex

putsex.result#=>100

end

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 747: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classStringAStringobjectholdsandmanipulatesanarbitrarysequenceofbytes,typicallyrepresentingcharacters.StringobjectsmaybecreatedusingString::neworasliterals.

Becauseofaliasingissues,usersofstringsshouldbeawareofthemethodsthatmodifythecontentsofaStringobject.Typically,methodswithnamesendingin“!''modifytheirreceiver,whilethosewithouta“!''returnanewString.However,thereareexceptions,suchasString#[]=.

InFilescomplex.cpack.crational.cstring.ctranscode.c

ParentObject

IncludedModulesComparable

Page 748: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

PublicClassMethods

Returnsanewstringobjectcontainingacopyofstr.

TrytoconvertobjintoaString,using#to_strmethod.Returnsconvertedstringornilifobjcannotbeconvertedforanyreason.

String.try_convert("str")#=>"str"

String.try_convert(/re/)#=>nil

PublicInstanceMethods

Format—Usesstrasaformatspecification,andreturnstheresultofapplyingittoarg.Iftheformatspecificationcontainsmorethanonesubstitution,thenargmustbeanArrayorHashcontainingthevaluestobesubstituted.SeeKernel::sprintffordetailsoftheformatstring.

"%05d"%123#=>"00123"

"%-5s:%08x"%["ID",self.object_id]#=>"ID:200e14d6"

"foo=%{foo}"%{:foo=>'bar'}#=>"foo=bar"

Copy—ReturnsanewStringcontainingintegercopiesofthereceiver.integermustbegreaterthanorequalto0.

new(str="")→new_str

try_convert(obj)→stringornil

str%arg→new_str

str*integer→new_str

Page 749: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

"Ho!"*3#=>"Ho!Ho!Ho!"

"Ho!"*0#=>""

Concatenation—ReturnsanewStringcontainingother_strconcatenatedtostr.

"Hellofrom"+self.to_s#=>"Hellofrommain"

Append—Concatenatesthegivenobjecttostr.IftheobjectisaInteger,itisconsideredasacodepoint,andisconvertedtoacharacterbeforeconcatenation.

a="hello"

a<<"world"#=>"helloworld"

a.concat(33)#=>"helloworld!"

Comparison—Returns-1,0,+1ornildependingonwhetherstringislessthan,equalto,orgreaterthanother_string.

nilisreturnedifthetwovaluesareincomparable.

Ifthestringsareofdifferentlengths,andthestringsareequalwhencompareduptotheshortestlength,thenthelongerstringisconsideredgreaterthantheshorterone.

<=>isthebasisforthemethods<,<=,>,>=,and

str+other_str→new_str

str<<integer→strconcat(integer)→strstr<<obj→strconcat(obj)→str

string<=>other_string→-1,0,+1ornil

Page 750: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

between?,includedfrommoduleComparable.ThemethodString#==doesnotuseComparable#==.

"abcdef"<=>"abcde"#=>1

"abcdef"<=>"abcdef"#=>0

"abcdef"<=>"abcdefg"#=>-1

"abcdef"<=>"ABCDEF"#=>1

EqualityReturnswhetherstr==obj,similartoObject#==.

IfobjisnotaninstanceofStringbutrespondstoto_str,thenthetwostringsarecomparedusingcaseequalityObject#===.

Otherwise,returnssimilarlyto#eql?,comparinglengthandcontent.

EqualityReturnswhetherstr==obj,similartoObject#==.

IfobjisnotaninstanceofStringbutrespondstoto_str,thenthetwostringsarecomparedusingcaseequalityObject#===.

Otherwise,returnssimilarlyto#eql?,comparinglengthandcontent.

str==obj→trueorfalsestr===obj→trueorfalse

str==obj→trueorfalsestr===obj→trueorfalse

str=~obj→fixnumornil

Page 751: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Match—IfobjisaRegexp,useitasapatterntomatchagainststr,andreturnsthepositionthematchstarts,ornilifthereisnomatch.Otherwise,invokesobj.=~,passingstrasanargument.Thedefault=~inObjectreturnsnil.

Note:str=~regexpisnotthesameasregexp=~str.Stringscapturedfromnamedcapturegroupsareassignedtolocalvariablesonlyinthesecondcase.

"cato'9tails"=~/\d/#=>7

"cato'9tails"=~9#=>nil

ElementReference—Ifpassedasingleindex,returnsasubstringofonecharacteratthatindex.Ifpassedastartindexandalength,returnsasubstringcontaininglengthcharactersstartingattheindex.Ifpassedarange,itsbeginningandendareinterpretedasoffsetsdelimitingthesubstringtobereturned.

Inthesethreecases,ifanindexisnegative,itis

str[index]→new_strornilstr[start,length]→new_strornilstr[range]→new_strornilstr[regexp]→new_strornilstr[regexp,capture]→new_strornilstr[match_str]→new_strornilslice(index)→new_strornilslice(start,length)→new_strornilslice(range)→new_strornilslice(regexp)→new_strornilslice(regexp,capture)→new_strornilslice(match_str)→new_strornil

Page 752: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

countedfromtheendofthestring.Forthestartandrangecasesthestartingindexisjustbeforeacharacterandanindexmatchingthestring'ssize.Additionally,anemptystringisreturnedwhenthestartingindexforacharacterrangeisattheendofthestring.

Returnsniliftheinitialindexfallsoutsidethestringorthelengthisnegative.

IfaRegexpissupplied,thematchingportionofthestringisreturned.Ifacapturefollowstheregularexpression,whichmaybeacapturegroupindexorname,followstheregularexpressionthatcomponentoftheMatchDataisreturnedinstead.

Ifamatch_strisgiven,thatstringisreturnedifitoccursinthestring.

Returnsniliftheregularexpressiondoesnotmatchorthematchstringcannotbefound.

a="hellothere"

a[1]#=>"e"

a[2,3]#=>"llo"

a[2..3]#=>"ll"

a[-3,2]#=>"er"

a[7..-2]#=>"her"

a[-4..-2]#=>"her"

a[-2..-4]#=>""

a[11,0]#=>""

a[11]#=>nil

a[12,0]#=>nil

a[12..-1]#=>nil

a[/[aeiou](.)\1/]#=>"ell"

a[/[aeiou](.)\1/,0]#=>"ell"

a[/[aeiou](.)\1/,1]#=>"l"

a[/[aeiou](.)\1/,2]#=>nil

Page 753: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/,"non_vowel"

a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/,"vowel"]

a["lo"]#=>"lo"

a["bye"]#=>nil

ElementAssignment—Replacessomeorallofthecontentofstr.TheportionofthestringaffectedisdeterminedusingthesamecriteriaasString#[].Ifthereplacementstringisnotthesamelengthasthetextitisreplacing,thestringwillbeadjustedaccordingly.Iftheregularexpressionorstringisusedastheindexdoesn'tmatchapositioninthestring,IndexErrorisraised.Iftheregularexpressionformisused,theoptionalsecondFixnumallowsyoutospecifywhichportionofthematchtoreplace(effectivelyusingtheMatchDataindexingrules.TheformsthattakeaFixnumwillraiseanIndexErrorifthevalueisoutofrange;theRangeformwillraiseaRangeError,andtheRegexpandStringwillraiseanIndexErroronnegativematch.

ReturnstrueforastringwhichhasonlyASCIIcharacters.

"abc".force_encoding("UTF-8").ascii_only?#=>true

str[fixnum]=new_strstr[fixnum,fixnum]=new_strstr[range]=aStringstr[regexp]=new_strstr[regexp,fixnum]=new_strstr[regexp,name]=new_strstr[other_str]=new_str

ascii_only?→trueorfalse

Page 754: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

"abc\u{6666}".force_encoding("UTF-8").ascii_only?#=>false

ReturnsacopiedstringwhoseencodingisASCII-8BIT.

Returnsanarrayofbytesinstr.Thisisashorthandforstr.each_byte.to_a.

Ifablockisgiven,whichisadeprecatedform,worksthesameaseach_byte.

Returnsthelengthofstrinbytes.

"\x80\u3042".bytesize#=>4

"hello".bytesize#=>5

ByteReference—IfpassedasingleFixnum,returnsasubstringofonebyteatthatposition.IfpassedtwoFixnumobjects,returnsasubstringstartingattheoffsetgivenbythefirst,andalengthgivenbythesecond.IfgivenaRange,asubstringcontainingbytesatoffsetsgivenbytherangeisreturned.Inallthreecases,ifanoffsetisnegative,itiscountedfromtheendofstr.Returnsniliftheinitialoffsetfallsoutsidethestring,thelengthisnegative,orthebeginningoftherangeisgreaterthantheend.Theencodingof

b→str

bytes→an_array

bytesize→integer

byteslice(fixnum)→new_strornilbyteslice(fixnum,fixnum)→new_strornilbyteslice(range)→new_strornil

Page 755: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

theresultedstringkeepsoriginalencoding.

"hello".byteslice(1)#=>"e"

"hello".byteslice(-1)#=>"o"

"hello".byteslice(1,2)#=>"el"

"\x80\u3042".byteslice(1,3)#=>"\u3042"

"\x03\u3042\xff".byteslice(1..3)#=>"\u3042"

Returnsacopyofstrwiththefirstcharacterconvertedtouppercaseandtheremaindertolowercase.Note:caseconversioniseffectiveonlyinASCIIregion.

"hello".capitalize#=>"Hello"

"HELLO".capitalize#=>"Hello"

"123ABC".capitalize#=>"123abc"

Modifiesstrbyconvertingthefirstcharactertouppercaseandtheremaindertolowercase.Returnsnilifnochangesaremade.Note:caseconversioniseffectiveonlyinASCIIregion.

a="hello"

a.capitalize!#=>"Hello"

a#=>"Hello"

a.capitalize!#=>nil

Case-insensitiveversionofString#<=>.

"abcdef".casecmp("abcde")#=>1

"aBcDeF".casecmp("abcdef")#=>0

"abcdef".casecmp("abcdefg")#=>-1

"abcdef".casecmp("ABCDEF")#=>0

capitalize→new_str

capitalize!→strornil

casecmp(other_str)→-1,0,+1ornil

Page 756: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Centersstrinwidth.Ifwidthisgreaterthanthelengthofstr,returnsanewStringoflengthwidthwithstrcenteredandpaddedwithpadstr;otherwise,returnsstr.

"hello".center(4)#=>"hello"

"hello".center(20)#=>"hello"

"hello".center(20,'123')#=>"1231231hello12312312"

Returnsanarrayofcharactersinstr.Thisisashorthandforstr.each_char.to_a.

Ifablockisgiven,whichisadeprecatedform,worksthesameaseach_char.

ReturnsanewStringwiththegivenrecordseparatorremovedfromtheendofstr(ifpresent).If$/hasnotbeenchangedfromthedefaultRubyrecordseparator,thenchompalsoremovescarriagereturncharacters(thatisitwillremove\n,\r,and\r\n).If$/isanemptystring,itwillremovealltrailingnewlinesfromthestring.

"hello".chomp#=>"hello"

"hello\n".chomp#=>"hello"

"hello\r\n".chomp#=>"hello"

"hello\n\r".chomp#=>"hello\n"

"hello\r".chomp#=>"hello"

"hello\nthere".chomp#=>"hello\nthere"

"hello".chomp("llo")#=>"he"

"hello\r\n\r\n".chomp('')#=>"hello"

"hello\r\n\r\r\n".chomp('')#=>"hello\r\n\r"

center(width,padstr='')→new_str

chars→an_array

chomp(separator=$/)→new_str

Page 757: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ModifiesstrinplaceasdescribedforString#chomp,returningstr,ornilifnomodificationsweremade.

ReturnsanewStringwiththelastcharacterremoved.Ifthestringendswith\r\n,bothcharactersareremoved.Applyingchoptoanemptystringreturnsanemptystring.String#chompisoftenasaferalternative,asitleavesthestringunchangedifitdoesn'tendinarecordseparator.

"string\r\n".chop#=>"string"

"string\n\r".chop#=>"string\n"

"string\n".chop#=>"string"

"string".chop#=>"strin"

"x".chop.chop#=>""

ProcessesstrasforString#chop,returningstr,ornilifstristheemptystring.SeealsoString#chomp!.

Returnsaone-characterstringatthebeginningofthestring.

a="abcde"

a.chr#=>"a"

Makesstringempty.

a="abcde"

chomp!(separator=$/)→strornil

chop→new_str

chop!→strornil

chr→string

clear→string

Page 758: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a.clear#=>""

ReturnsanarrayoftheIntegerordinalsofthecharactersinstr.Thisisashorthandforstr.each_codepoint.to_a.

Ifablockisgiven,whichisadeprecatedform,worksthesameaseach_codepoint.

Append—Concatenatesthegivenobjecttostr.IftheobjectisaInteger,itisconsideredasacodepoint,andisconvertedtoacharacterbeforeconcatenation.

a="hello"

a<<"world"#=>"helloworld"

a.concat(33)#=>"helloworld!"

Eachother_strparameterdefinesasetofcharacterstocount.Theintersectionofthesesetsdefinesthecharacterstocountinstr.Anyother_strthatstartswithacaret^isnegated.Thesequencec1-c2meansallcharactersbetweenc1andc2.Thebackslashcharacter\</code>canbeusedtoescape<code>^or-andisotherwiseignoredunlessitappearsattheendofasequenceortheendofaother_str.

a="helloworld"

a.count"lo"#=>5

codepoints→an_array

str<<integer→strconcat(integer)→strstr<<obj→strconcat(obj)→str

count([other_str]+)→fixnum

Page 759: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a.count"lo","o"#=>2

a.count"hello","^l"#=>4

a.count"ej-m"#=>4

"hello^world".count"\\^aeiou"#=>4

"hello-world".count"a\\-eo"#=>4

c="helloworld\\r\\n"

c.count"\\"#=>2

c.count"\\A"#=>0

c.count"X-\\w"#=>3

Appliesaone-waycryptographichashtostrbyinvokingthestandardlibraryfunctioncrypt(3)withthegivensaltstring.Whiletheformatandtheresultaresystemandimplementationdependent,usingasaltmatchingtheregularexpression\A[a-zA-Z0-9./]{2}shouldbevalidandsafeonanyplatform,inwhichonlythefirsttwocharactersaresignificant.

Thismethodisforuseinsystemspecificscripts,soifyouwantacross-platformhashfunctionconsiderusingDigestorOpenSSLinstead.

Returnsacopyofstrwithallcharactersintheintersectionofitsargumentsdeleted.UsesthesamerulesforbuildingthesetofcharactersasString#count.

"hello".delete"l","lo"#=>"heo"

"hello".delete"lo"#=>"he"

"hello".delete"aeiou","^e"#=>"hell"

"hello".delete"ej-m"#=>"ho"

crypt(salt_str)→new_str

delete([other_str]+)→new_str

delete!([other_str]+)→strornil

Page 760: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Performsadeleteoperationinplace,returningstr,ornilifstrwasnotmodified.

Returnsacopyofstrwithalluppercaselettersreplacedwiththeirlowercasecounterparts.Theoperationislocaleinsensitive—onlycharacters“A''to“Z''areaffected.Note:casereplacementiseffectiveonlyinASCIIregion.

"hEllO".downcase#=>"hello"

Downcasesthecontentsofstr,returningnilifnochangesweremade.Note:casereplacementiseffectiveonlyinASCIIregion.

Producesaversionofstrwithallnon-printingcharactersreplacedby\nnnnotationandallspecialcharactersescaped.

"hello\n''".dump#=>"\"hello\\n''\"

Passeseachbyteinstrtothegivenblock,orreturnsanenumeratorifnoblockisgiven.

"hello".each_byte{|c|printc,''}

produces:

104101108108111

downcase→new_str

downcase!→strornil

dump→new_str

each_byte{|fixnum|block}→streach_byte→an_enumerator

Page 761: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Passeseachcharacterinstrtothegivenblock,orreturnsanenumeratorifnoblockisgiven.

"hello".each_char{|c|printc,''}

produces:

hello

PassestheIntegerordinalofeachcharacterinstr,alsoknownasacodepointwhenappliedtoUnicodestringstothegivenblock.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

"hello\u0639".each_codepoint{|c|printc,''}

produces:

1041011081081111593

Splitsstrusingthesuppliedparameterastherecordseparator($/bydefault),passingeachsubstringinturntothesuppliedblock.Ifazero-lengthrecordseparatorissupplied,thestringissplitintoparagraphsdelimitedbymultiplesuccessive

each_char{|cstr|block}→streach_char→an_enumerator

each_codepoint{|integer|block}→streach_codepoint→an_enumerator

each_line(separator=$/){|substr|block}→streach_line(separator=$/)→an_enumerator

Page 762: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

newlines.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

print"Exampleone\n"

"hello\nworld".each_line{|s|ps}

print"Exampletwo\n"

"hello\nworld".each_line('l'){|s|ps}

print"Examplethree\n"

"hello\n\n\nworld".each_line(''){|s|ps}

produces:

Exampleone

"hello\n"

"world"

Exampletwo

"hel"

"l"

"o\nworl"

"d"

Examplethree

"hello\n\n\n"

"world"

Returnstrueifstrhasalengthofzero.

"hello".empty?#=>false

"".empty?#=>false

"".empty?#=>true

Thefirstformreturnsacopyofstrtranscodedtoencodingencoding.Thesecondformreturnsacopy

empty?→trueorfalse

encode(encoding[,options])→strencode(dst_encoding,src_encoding[,options])→strencode([options])→str

Page 763: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ofstrtranscodedfromsrc_encodingtodst_encoding.ThelastformreturnsacopyofstrtranscodedtoEncoding.default_internal.

Bydefault,thefirstandsecondformraiseEncoding::UndefinedConversionErrorforcharactersthatareundefinedinthedestinationencoding,andEncoding::InvalidByteSequenceErrorforinvalidbytesequencesinthesourceencoding.Thelastformbydefaultdoesnotraiseexceptionsbutusesreplacementstrings.

TheoptionsHashgivesdetailsforconversionandcanhavethefollowingkeys:

:invalidIfthevalueis:replace,encodereplacesinvalidbytesequencesinstrwiththereplacementcharacter.ThedefaultistoraisetheEncoding::InvalidByteSequenceErrorexception

:undefIfthevalueis:replace,encodereplacescharacterswhichareundefinedinthedestinationencodingwiththereplacementcharacter.ThedefaultistoraisetheEncoding::UndefinedConversionError.

:replaceSetsthereplacementstringtothegivenvalue.Thedefaultreplacementstringis“uFFFD”forUnicodeencodingforms,and“?”otherwise.

:fallbackSetsthereplacementstringbythegivenobjectforundefinedcharacter.TheobjectshouldbeaHash,aProc,aMethod,oranobjectwhichhas[]method.Itskeyisanundefinedcharacterencodedinthesourceencodingofcurrenttranscoder.Its

Page 764: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

valuecanbeanyencodinguntilitcanbeconvertedintothedestinationencodingofthetranscoder.

:xmlThevaluemustbe:textor:attr.Ifthevalueis:textencodereplacesundefinedcharacterswiththeir(upper-casehexadecimal)numericcharacterreferences.'&','<',and'>'areconvertedto“&amp;”,“&lt;”,and“&gt;”,respectively.Ifthevalueis:attr,encodealsoquotesthereplacementresult(using'“'),andreplaces'”'with“&quot;”.

:cr_newlineReplacesLF(“n”)withCR(“r”)ifvalueistrue.

:crlf_newlineReplacesLF(“n”)withCRLF(“rn”)ifvalueistrue.

:universal_newlineReplacesCRLF(“rn”)andCR(“r”)withLF(“n”)ifvalueistrue.

Thefirstformtranscodesthecontentsofstrfromstr.encodingtoencoding.Thesecondformtranscodesthecontentsofstrfromsrc_encodingtodst_encoding.TheoptionsHashgivesdetailsforconversion.See#encodefordetails.Returnsthestringevenifnochangesweremade.

ReturnstheEncodingobjectthatrepresentstheencodingofobj.

encode!(encoding[,options])→strencode!(dst_encoding,src_encoding[,options])→str

encoding→encoding

Page 765: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifstrendswithoneofthesuffixesgiven.

Twostringsareequaliftheyhavethesamelengthandcontent.

Changestheencodingtoencodingandreturnsself.

returnstheindexthbyteasaninteger.

Returnsacopyofstrwiththealloccurrencesofpatternsubstitutedforthesecondargument.ThepatternistypicallyaRegexp;ifgivenasaString,anyregularexpressionmetacharactersitcontainswillbeinterpretedliterally,e.g.'\\d'willmatchabacklashfollowedby'd',insteadofadigit.

IfreplacementisaStringitwillbesubstitutedforthematchedtext.Itmaycontainback-referencestothepattern'scapturegroupsoftheform\\d,wheredisagroupnumber,or\\k<n>,wherenisagroupname.Ifitisadouble-quotedstring,bothback-referencesmustbeprecededbyanadditionalbackslash.

end_with?([suffixes]+)→trueorfalse

eql?(other)→trueorfalse

force_encoding(encoding)→str

getbyte(index)→0..255

gsub(pattern,replacement)→new_strgsub(pattern,hash)→new_strgsub(pattern){|match|block}→new_strgsub(pattern)→enumerator

Page 766: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

However,withinreplacementthespecialmatchvariables,suchas$&,willnotrefertothecurrentmatch.

IfthesecondargumentisaHash,andthematchedtextisoneofitskeys,thecorrespondingvalueisthereplacementstring.

Intheblockform,thecurrentmatchstringispassedinasaparameter,andvariablessuchas$1,$2,$`,$&,and$'willbesetappropriately.Thevaluereturnedbytheblockwillbesubstitutedforthematchoneachcall.

Theresultinheritsanytaintingintheoriginalstringoranysuppliedreplacementstring.

Whenneitherablocknorasecondargumentissupplied,anEnumeratorisreturned.

"hello".gsub(/[aeiou]/,'*')#=>"h*ll*"

"hello".gsub(/([aeiou])/,'<\1>')#=>"h<e>ll<o>"

"hello".gsub(/./){|s|s.ord.to_s+''}#=>"104101108108111"

"hello".gsub(/(?<foo>[aeiou])/,'{\k<foo>}')#=>"h{e}ll{o}"

'hello'.gsub(/[eo]/,'e'=>3,'o'=>'*')#=>"h3ll*"

PerformsthesubstitutionsofString#gsubinplace,returningstr,ornilifnosubstitutionswereperformed.Ifnoblockandnoreplacementisgiven,anenumeratorisreturnedinstead.

Returnahashbasedonthestring'slength,contentandencoding.

gsub!(pattern,replacement)→strornilgsub!(pattern){|match|block}→strornilgsub!(pattern)→an_enumerator

hash→fixnum

Page 767: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

SeealsoObject#hash.

Treatsleadingcharactersfromstrasastringofhexadecimaldigits(withanoptionalsignandanoptional0x)andreturnsthecorrespondingnumber.Zeroisreturnedonerror.

"0x0a".hex#=>10

"-1234".hex#=>-4660

"0".hex#=>0

"wombat".hex#=>0

Returnstrueifstrcontainsthegivenstringorcharacter.

"hello".include?"lo"#=>true

"hello".include?"ol"#=>false

"hello".include?h#=>true

Returnstheindexofthefirstoccurrenceofthegivensubstringorpattern(regexp)instr.Returnsnilifnotfound.Ifthesecondparameterispresent,itspecifiesthepositioninthestringtobeginthesearch.

"hello".index('e')#=>1

"hello".index('lo')#=>3

"hello".index('a')#=>nil

"hello".index(e)#=>1

"hello".index(/[aeiou]/,-3)#=>4

hex→integer

include?other_str→trueorfalse

index(substring[,offset])→fixnumornilindex(regexp[,offset])→fixnumornil

replace(other_str)→str

Page 768: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Replacesthecontentsandtaintednessofstrwiththecorrespondingvaluesinother_str.

s="hello"#=>"hello"

s.replace"world"#=>"world"

Insertsother_strbeforethecharacteratthegivenindex,modifyingstr.Negativeindicescountfromtheendofthestring,andinsertafterthegivencharacter.TheintentisinsertaStringsothatitstartsatthegivenindex.

"abcd".insert(0,'X')#=>"Xabcd"

"abcd".insert(3,'X')#=>"abcXd"

"abcd".insert(4,'X')#=>"abcdX"

"abcd".insert(-3,'X')#=>"abXcd"

"abcd".insert(-1,'X')#=>"abcdX"

Returnsaprintableversionofstr,surroundedbyquotemarks,withspecialcharactersescaped.

str="hello"

str[3]="\b"

str.inspect#=>"\"hel\\bo\""

ReturnstheSymbolcorrespondingtostr,creatingthesymbolifitdidnotpreviouslyexist.SeeSymbol#id2name.

"Koala".intern#=>:Koala

s='cat'.to_sym#=>:cat

s==:cat#=>true

s='@cat'.to_sym#=>:@cat

insert(index,other_str)→str

inspect→string

intern→symbolto_sym→symbol

Page 769: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

s==:@cat#=>true

Thiscanalsobeusedtocreatesymbolsthatcannotberepresentedusingthe:xxxnotation.

'catanddog'.to_sym#=>:"catanddog"

Returnsthecharacterlengthofstr.

Returnsanarrayoflinesinstrsplitusingthesuppliedrecordseparator($/bydefault).Thisisashorthandforstr.each_line(separator).to_a.

Ifablockisgiven,whichisadeprecatedform,worksthesameaseach_line.

Ifintegerisgreaterthanthelengthofstr,returnsanewStringoflengthintegerwithstrleftjustifiedandpaddedwithpadstr;otherwise,returnsstr.

"hello".ljust(4)#=>"hello"

"hello".ljust(20)#=>"hello"

"hello".ljust(20,'1234')#=>"hello123412341234123"

Returnsacopyofstrwithleadingwhitespaceremoved.SeealsoString#rstripandString#strip.

"hello".lstrip#=>"hello"

"hello".lstrip#=>"hello"

length→integersize→integer

lines(separator=$/)→an_array

ljust(integer,padstr='')→new_str

lstrip→new_str

Page 770: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Removesleadingwhitespacefromstr,returningnilifnochangewasmade.SeealsoString#rstrip!andString#strip!.

"hello".lstrip#=>"hello"

"hello".lstrip!#=>nil

ConvertspatterntoaRegexp(ifitisn'talreadyone),theninvokesitsmatchmethodonstr.Ifthesecondparameterispresent,itspecifiesthepositioninthestringtobeginthesearch.

'hello'.match('(.)\1')#=>#<MatchData"ll"1:"l">

'hello'.match('(.)\1')[0]#=>"ll"

'hello'.match(/(.)\1/)[0]#=>"ll"

'hello'.match('xx')#=>nil

Ifablockisgiven,invoketheblockwithMatchDataifmatchsucceed,sothatyoucanwrite

str.match(pat){|m|...}

insteadof

ifm=str.match(pat)

...

end

Thereturnvalueisavaluefromblockexecutioninthiscase.

lstrip!→selfornil

match(pattern)→matchdataornilmatch(pattern,pos)→matchdataornil

succ→new_strnext→new_str

Page 771: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthesuccessortostr.Thesuccessoriscalculatedbyincrementingcharactersstartingfromtherightmostalphanumeric(ortherightmostcharacteriftherearenoalphanumerics)inthestring.Incrementingadigitalwaysresultsinanotherdigit,andincrementingaletterresultsinanotherletterofthesamecase.Incrementingnonalphanumericsusestheunderlyingcharacterset'scollatingsequence.

Iftheincrementgeneratesa“carry,''thecharactertotheleftofitisincremented.Thisprocessrepeatsuntilthereisnocarry,addinganadditionalcharacterifnecessary.

"abcd".succ#=>"abce"

"THX1138".succ#=>"THX1139"

"<<koala>>".succ#=>"<<koalb>>"

"1999zzz".succ#=>"2000aaa"

"ZZZ9999".succ#=>"AAAA0000"

"***".succ#=>"**+"

EquivalenttoString#succ,butmodifiesthereceiverinplace.

Treatsleadingcharactersofstrasastringofoctaldigits(withanoptionalsign)andreturnsthecorrespondingnumber.Returns0iftheconversionfails.

"123".oct#=>83

"-377".oct#=>-255

"bad".oct#=>0

"0377bad".oct#=>255

succ!→strnext!→str

oct→integer

Page 772: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturntheIntegerordinalofaone-characterstring.

"a".ord#=>97

Searchesseporpattern(regexp)inthestringandreturnsthepartbeforeit,thematch,andthepartafterit.Ifitisnotfound,returnstwoemptystringsandstr.

"hello".partition("l")#=>["he","l","lo"]

"hello".partition("x")#=>["hello","",""]

"hello".partition(/.l/)#=>["h","el","lo"]

Prepend—Prependthegivenstringtostr.

a="world"

a.prepend("hello")#=>"helloworld"

a#=>"helloworld"

Replacesthecontentsandtaintednessofstrwiththecorrespondingvaluesinother_str.

s="hello"#=>"hello"

s.replace"world"#=>"world"

Returnsanewstringwiththecharactersfromstrinreverseorder.

ord→integer

partition(sep)→[head,sep,tail]partition(regexp)→[head,match,tail]

prepend(other_str)→str

replace(other_str)→str

reverse→new_str

Page 773: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

"stressed".reverse#=>"desserts"

Reversesstrinplace.

Returnstheindexofthelastoccurrenceofthegivensubstringorpattern(regexp)instr.Returnsnilifnotfound.Ifthesecondparameterispresent,itspecifiesthepositioninthestringtoendthesearch—charactersbeyondthispointwillnotbeconsidered.

"hello".rindex('e')#=>1

"hello".rindex('l')#=>3

"hello".rindex('a')#=>nil

"hello".rindex(e)#=>1

"hello".rindex(/[aeiou]/,-2)#=>1

Ifintegerisgreaterthanthelengthofstr,returnsanewStringoflengthintegerwithstrrightjustifiedandpaddedwithpadstr;otherwise,returnsstr.

"hello".rjust(4)#=>"hello"

"hello".rjust(20)#=>"hello"

"hello".rjust(20,'1234')#=>"123412341234123hello"

Searchesseporpattern(regexp)inthestringfromtheendofthestring,andreturnsthepartbeforeit,thematch,andthepartafterit.Ifitisnotfound,

reverse!→str

rindex(substring[,fixnum])→fixnumornilrindex(regexp[,fixnum])→fixnumornil

rjust(integer,padstr='')→new_str

rpartition(sep)→[head,sep,tail]rpartition(regexp)→[head,match,tail]

Page 774: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

returnstwoemptystringsandstr.

"hello".rpartition("l")#=>["hel","l","o"]

"hello".rpartition("x")#=>["","","hello"]

"hello".rpartition(/.l/)#=>["he","ll","o"]

Returnsacopyofstrwithtrailingwhitespaceremoved.SeealsoString#lstripandString#strip.

"hello".rstrip#=>"hello"

"hello".rstrip#=>"hello"

Removestrailingwhitespacefromstr,returningnilifnochangewasmade.SeealsoString#lstrip!andString#strip!.

"hello".rstrip#=>"hello"

"hello".rstrip!#=>nil

Bothformsiteratethroughstr,matchingthepattern(whichmaybeaRegexporaString).Foreachmatch,aresultisgeneratedandeitheraddedtotheresultarrayorpassedtotheblock.Ifthepatterncontainsnogroups,eachindividualresultconsistsofthematchedstring,$&.Ifthepatterncontainsgroups,eachindividualresultisitselfanarraycontainingoneentrypergroup.

a="cruelworld"

a.scan(/\w+/)#=>["cruel","world"]

a.scan(/.../)#=>["cru","el","wor"]

rstrip→new_str

rstrip!→selfornil

scan(pattern)→arrayscan(pattern){|match,...|block}→str

Page 775: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a.scan(/(...)/)#=>[["cru"],["el"],["wor"]]

a.scan(/(..)(..)/)#=>[["cr","ue"],["l","wo"]]

Andtheblockform:

a.scan(/\w+/){|w|print"<<#{w}>>"}

print"\n"

a.scan(/(.)(.)/){|x,y|printy,x}

print"\n"

produces:

<<cruel>><<world>>

rceulowlr

Ifthestringisinvalidbytesequencethenreplaceinvalidbyteswithgivenreplacementcharacter,elsereturnsself.Ifblockisgiven,replaceinvalidbyteswithreturnedvalueoftheblock.

"abc\u3042\x81".scrub#=>"abc\u3042\uFFFD"

"abc\u3042\x81".scrub("*")#=>"abc\u3042*"

"abc\u3042\xE3\x80".scrub{|bytes|'<'+bytes.unpack('H*'

Ifthestringisinvalidbytesequencethenreplaceinvalidbyteswithgivenreplacementcharacter,elsereturnsself.Ifblockisgiven,replaceinvalidbyteswithreturnedvalueoftheblock.

"abc\u3042\x81".scrub!#=>"abc\u3042\uFFFD"

"abc\u3042\x81".scrub!("*")#=>"abc\u3042*"

scrub→new_strscrub(repl)→new_strscrub{|bytes|}→new_str

scrub!→strscrub!(repl)→strscrub!{|bytes|}→str

Page 776: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

"abc\u3042\xE3\x80".scrub!{|bytes|'<'+bytes.unpack('H*'

modifiestheindexthbyteasinteger.

Returnsthecharacterlengthofstr.

ElementReference—Ifpassedasingleindex,returnsasubstringofonecharacteratthatindex.Ifpassedastartindexandalength,returnsasubstringcontaininglengthcharactersstartingattheindex.Ifpassedarange,itsbeginningandendareinterpretedasoffsetsdelimitingthesubstringtobereturned.

Inthesethreecases,ifanindexisnegative,itiscountedfromtheendofthestring.Forthestartand

setbyte(index,integer)→integer

length→integersize→integer

str[index]→new_strornilstr[start,length]→new_strornilstr[range]→new_strornilstr[regexp]→new_strornilstr[regexp,capture]→new_strornilstr[match_str]→new_strornilslice(index)→new_strornilslice(start,length)→new_strornilslice(range)→new_strornilslice(regexp)→new_strornilslice(regexp,capture)→new_strornilslice(match_str)→new_strornil

Page 777: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

rangecasesthestartingindexisjustbeforeacharacterandanindexmatchingthestring'ssize.Additionally,anemptystringisreturnedwhenthestartingindexforacharacterrangeisattheendofthestring.

Returnsniliftheinitialindexfallsoutsidethestringorthelengthisnegative.

IfaRegexpissupplied,thematchingportionofthestringisreturned.Ifacapturefollowstheregularexpression,whichmaybeacapturegroupindexorname,followstheregularexpressionthatcomponentoftheMatchDataisreturnedinstead.

Ifamatch_strisgiven,thatstringisreturnedifitoccursinthestring.

Returnsniliftheregularexpressiondoesnotmatchorthematchstringcannotbefound.

a="hellothere"

a[1]#=>"e"

a[2,3]#=>"llo"

a[2..3]#=>"ll"

a[-3,2]#=>"er"

a[7..-2]#=>"her"

a[-4..-2]#=>"her"

a[-2..-4]#=>""

a[11,0]#=>""

a[11]#=>nil

a[12,0]#=>nil

a[12..-1]#=>nil

a[/[aeiou](.)\1/]#=>"ell"

a[/[aeiou](.)\1/,0]#=>"ell"

a[/[aeiou](.)\1/,1]#=>"l"

a[/[aeiou](.)\1/,2]#=>nil

a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/,"non_vowel"

a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/,"vowel"]

Page 778: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a["lo"]#=>"lo"

a["bye"]#=>nil

Deletesthespecifiedportionfromstr,andreturnstheportiondeleted.

string="thisisastring"

string.slice!(2)#=>"i"

string.slice!(3..6)#=>"is"

string.slice!(/s.*t/)#=>"sast"

string.slice!("r")#=>"r"

string#=>"thing"

Dividesstrintosubstringsbasedonadelimiter,returninganarrayofthesesubstrings.

IfpatternisaString,thenitscontentsareusedasthedelimiterwhensplittingstr.Ifpatternisasinglespace,strissplitonwhitespace,withleadingwhitespaceandrunsofcontiguouswhitespacecharactersignored.

IfpatternisaRegexp,strisdividedwherethepatternmatches.Wheneverthepatternmatchesazero-lengthstring,strissplitintoindividualcharacters.Ifpatterncontainsgroups,therespectivematcheswillbereturnedinthearrayaswell.

Ifpatternisomitted,thevalueof$;isused.If$;isnil(whichisthedefault),strissplitonwhitespaceas

slice!(fixnum)→new_strornilslice!(fixnum,fixnum)→new_strornilslice!(range)→new_strornilslice!(regexp)→new_strornilslice!(other_str)→new_strornil

split(pattern=$;,[limit])→anArray

Page 779: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

if`'werespecified.

Ifthelimitparameterisomitted,trailingnullfieldsaresuppressed.Iflimitisapositivenumber,atmostthatnumberoffieldswillbereturned(iflimitis1,theentirestringisreturnedastheonlyentryinanarray).Ifnegative,thereisnolimittothenumberoffieldsreturned,andtrailingnullfieldsarenotsuppressed.

WhentheinputstrisemptyanemptyArrayisreturnedasthestringisconsideredtohavenofieldstosplit.

"now'sthetime".split#=>["now's","the","time"]

"now'sthetime".split('')#=>["now's","the","time"]

"now'sthetime".split(//)#=>["","now's","","the","time"]

"1,2.34,56,7".split(%r{,\s*})#=>["1","2.34","56","7"]

"hello".split(//)#=>["h","e","l","l","o"]

"hello".split(//,3)#=>["h","e","llo"]

"himom".split(%r{\s*})#=>["h","i","m","o","m"]

"mellowyellow".split("ello")#=>["m","wy","w"]

"1,2,,3,4,,".split(',')#=>["1","2","","3","4"]

"1,2,,3,4,,".split(',',4)#=>["1","2","","3,4,,"]

"1,2,,3,4,,".split(',',-4)#=>["1","2","","3","4","",""]

"".split(',',-1)#=>[]

Buildsasetofcharactersfromtheother_strparameter(s)usingtheproceduredescribedforString#count.Returnsanewstringwhererunsofthesamecharacterthatoccurinthissetarereplacedbyasinglecharacter.Ifnoargumentsaregiven,allrunsofidenticalcharactersarereplacedbyasinglecharacter.

"yellowmoon".squeeze#=>"yelowmon"

"nowisthe".squeeze("")#=>"nowisthe"

"puttersshootballs".squeeze("m-z")#=>"putersshotballs"

squeeze([other_str]*)→new_str

Page 780: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Squeezesstrinplace,returningeitherstr,ornilifnochangesweremade.

Returnstrueifstrstartswithoneoftheprefixesgiven.

"hello".start_with?("hell")#=>true

#returnstrueifoneoftheprefixesmatches.

"hello".start_with?("heaven","hell")#=>true

"hello".start_with?("heaven","paradise")#=>false

Returnsacopyofstrwithleadingandtrailingwhitespaceremoved.

"hello".strip#=>"hello"

"\tgoodbye\r\n".strip#=>"goodbye"

Removesleadingandtrailingwhitespacefromstr.Returnsnilifstrwasnotaltered.

Returnsacopyofstrwiththefirstoccurrenceofpatternreplacedbythesecondargument.ThepatternistypicallyaRegexp;ifgivenasaString,any

squeeze!([other_str]*)→strornil

start_with?([prefixes]+)→trueorfalse

strip→new_str

strip!→strornil

sub(pattern,replacement)→new_strsub(pattern,hash)→new_strsub(pattern){|match|block}→new_str

Page 781: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

regularexpressionmetacharactersitcontainswillbeinterpretedliterally,e.g.'\\d'willmatchabacklashfollowedby'd',insteadofadigit.

IfreplacementisaStringitwillbesubstitutedforthematchedtext.Itmaycontainback-referencestothepattern'scapturegroupsoftheform"\d",wheredisagroupnumber,or"\k<n>",wherenisagroupname.Ifitisadouble-quotedstring,bothback-referencesmustbeprecededbyanadditionalbackslash.However,withinreplacementthespecialmatchvariables,suchas&$,willnotrefertothecurrentmatch.IfreplacementisaStringthatlookslikeapattern'scapturegroupbutisactaullynotapatterncapturegroupe.g."\'",thenitwillhavetobeprecededbytwobackslasheslikeso"\\'".

IfthesecondargumentisaHash,andthematchedtextisoneofitskeys,thecorrespondingvalueisthereplacementstring.

Intheblockform,thecurrentmatchstringispassedinasaparameter,andvariablessuchas$1,$2,$`,$&,and$'willbesetappropriately.Thevaluereturnedbytheblockwillbesubstitutedforthematchoneachcall.

Theresultinheritsanytaintingintheoriginalstringoranysuppliedreplacementstring.

"hello".sub(/[aeiou]/,'*')#=>"h*llo"

"hello".sub(/([aeiou])/,'<\1>')#=>"h<e>llo"

"hello".sub(/./){|s|s.ord.to_s+''}#=>"104ello"

"hello".sub(/(?<foo>[aeiou])/,'*\k<foo>*')#=>"h*e*llo"

'IsSHELLyourpreferredshell?'.sub(/[[:upper:]]{2,}/

#=>"Is/bin/bashyourpreferredshell?"

sub!(pattern,replacement)→strornil

Page 782: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Performsthesamesubstitutionas#subin-place.

Returnsstrifasubstitutionwasperformedornilifnosubstitutionwasperformed.

Returnsthesuccessortostr.Thesuccessoriscalculatedbyincrementingcharactersstartingfromtherightmostalphanumeric(ortherightmostcharacteriftherearenoalphanumerics)inthestring.Incrementingadigitalwaysresultsinanotherdigit,andincrementingaletterresultsinanotherletterofthesamecase.Incrementingnonalphanumericsusestheunderlyingcharacterset'scollatingsequence.

Iftheincrementgeneratesa“carry,''thecharactertotheleftofitisincremented.Thisprocessrepeatsuntilthereisnocarry,addinganadditionalcharacterifnecessary.

"abcd".succ#=>"abce"

"THX1138".succ#=>"THX1139"

"<<koala>>".succ#=>"<<koalb>>"

"1999zzz".succ#=>"2000aaa"

"ZZZ9999".succ#=>"AAAA0000"

"***".succ#=>"**+"

EquivalenttoString#succ,butmodifiesthereceiverinplace.

Returnsabasicn-bitchecksumofthecharactersin

sub!(pattern){|match|block}→strornil

succ→new_strnext→new_str

succ!→strnext!→str

sum(n=16)→integer

Page 783: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

str,wherenistheoptionalFixnumparameter,defaultingto16.Theresultissimplythesumofthebinaryvalueofeachbyteinstrmodulo2**n-1.Thisisnotaparticularlygoodchecksum.

Returnsacopyofstrwithuppercasealphabeticcharactersconvertedtolowercaseandlowercasecharactersconvertedtouppercase.Note:caseconversioniseffectiveonlyinASCIIregion.

"Hello".swapcase#=>"hELLO"

"cYbEr_PuNk11".swapcase#=>"CyBeR_pUnK11"

EquivalenttoString#swapcase,butmodifiesthereceiverinplace,returningstr,ornilifnochangesweremade.Note:caseconversioniseffectiveonlyinASCIIregion.

Returnsacomplexwhichdenotesthestringform.Theparserignoresleadingwhitespacesandtrailinggarbage.Anydigitsequencescanbeseparatedbyanunderscore.Returnszerofornullorgarbagestring.

'9'.to_c#=>(9+0i)

'2.5'.to_c#=>(2.5+0i)

'2.5/1'.to_c#=>((5/2)+0i)

'-3/2'.to_c#=>((-3/2)+0i)

'-i'.to_c#=>(0-1i)

'45i'.to_c#=>(0+45i)

'3-4i'.to_c#=>(3-4i)

'-4e2-4e-2i'.to_c#=>(-400.0-0.04i)

'-0.0-0.0i'.to_c#=>(-0.0-0.0i)

'1/2+3/4i'.to_c#=>((1/2)+(3/4)*i)

swapcase→new_str

swapcase!→strornil

to_c→complex

Page 784: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

'ruby'.to_c#=>(0+0i)

SeeKernel.Complex.

Returnstheresultofinterpretingleadingcharactersinstrasafloatingpointnumber.Extraneouscharacterspasttheendofavalidnumberareignored.Ifthereisnotavalidnumberatthestartofstr,0.0isreturned.Thismethodneverraisesanexception.

"123.45e1".to_f#=>1234.5

"45.67degrees".to_f#=>45.67

"thx1138".to_f#=>0.0

Returnstheresultofinterpretingleadingcharactersinstrasanintegerbasebase(between2and36).Extraneouscharacterspasttheendofavalidnumberareignored.Ifthereisnotavalidnumberatthestartofstr,0isreturned.Thismethodneverraisesanexceptionwhenbaseisvalid.

"12345".to_i#=>12345

"99redballoons".to_i#=>99

"0a".to_i#=>0

"0a".to_i(16)#=>10

"hello".to_i#=>0

"1100101".to_i(2)#=>101

"1100101".to_i(8)#=>294977

"1100101".to_i(10)#=>1100101

"1100101".to_i(16)#=>17826049

Returnsarationalwhichdenotesthestringform.Theparserignoresleadingwhitespacesandtrailing

to_f→float

to_i(base=10)→integer

to_r→rational

Page 785: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

garbage.Anydigitsequencescanbeseparatedbyanunderscore.Returnszerofornullorgarbagestring.

NOTE:'0.3'.#to_risn'tthesameas0.3.to_r.Theformerisequivalentto'3/10'.#to_r,butthelatterisn'tso.

'2'.to_r#=>(2/1)

'300/2'.to_r#=>(150/1)

'-9.2'.to_r#=>(-46/5)

'-9.2e2'.to_r#=>(-920/1)

'1_234_567'.to_r#=>(1234567/1)

'21june09'.to_r#=>(21/1)

'21/06/09'.to_r#=>(7/2)

'bwv1079'.to_r#=>(0/1)

SeeKernel.Rational.

Returnsthereceiver.

Returnsthereceiver.

ReturnstheSymbolcorrespondingtostr,creatingthesymbolifitdidnotpreviouslyexist.SeeSymbol#id2name.

"Koala".intern#=>:Koala

s='cat'.to_sym#=>:cat

s==:cat#=>true

s='@cat'.to_sym#=>:@cat

s==:@cat#=>true

to_s→strto_str→str

to_s→strto_str→str

intern→symbolto_sym→symbol

Page 786: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thiscanalsobeusedtocreatesymbolsthatcannotberepresentedusingthe:xxxnotation.

'catanddog'.to_sym#=>:"catanddog"

Returnsacopyofstrwiththecharactersinfrom_strreplacedbythecorrespondingcharactersinto_str.Ifto_strisshorterthanfrom_str,itispaddedwithitslastcharacterinordertomaintainthecorrespondence.

"hello".tr('el','ip')#=>"hippo"

"hello".tr('aeiou','*')#=>"h*ll*"

"hello".tr('aeiou','AA*')#=>"hAll*"

Bothstringsmayusethec1-c2notationtodenoterangesofcharacters,andfrom_strmaystartwitha^,whichdenotesallcharactersexceptthoselisted.

"hello".tr('a-y','b-z')#=>"ifmmp"

"hello".tr('^aeiou','*')#=>"*e**o"

Thebackslashcharacter</code>canbeusedtoescape<code>^or-andisotherwiseignoredunlessitappearsattheendofarangeortheendofthefrom_strorto_str:

"hello^world".tr("\\^aeiou","*")#=>"h*ll**w*rld"

"hello-world".tr("a\\-eo","*")#=>"h*ll**w*rld"

"hello\r\nworld".tr("\r","")#=>"hello\nworld"

"hello\r\nworld".tr("\\r","")#=>"hello\r\nwold"

"hello\r\nworld".tr("\\\r","")#=>"hello\nworld"

"X['\\b']".tr("X\\","")#=>"['b']"

"X['\\b']".tr("X-\\]","")#=>"'b'"

tr(from_str,to_str)→new_str

Page 787: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Translatesstrinplace,usingthesamerulesasString#tr.Returnsstr,ornilifnochangesweremade.

ProcessesacopyofstrasdescribedunderString#tr,thenremovesduplicatecharactersinregionsthatwereaffectedbythetranslation.

"hello".tr_s('l','r')#=>"hero"

"hello".tr_s('el','*')#=>"h*o"

"hello".tr_s('el','hx')#=>"hhxo"

PerformsString#tr_sprocessingonstrinplace,returningstr,ornilifnochangesweremade.

Decodesstr(whichmaycontainbinarydata)accordingtotheformatstring,returninganarrayofeachvalueextracted.Theformatstringconsistsofasequenceofsingle-characterdirectives,summarizedinthetableattheendofthisentry.Eachdirectivemaybefollowedbyanumber,indicatingthenumberoftimestorepeatwiththisdirective.Anasterisk(“*'')willuseupallremainingelements.ThedirectivessSiIlLmayeachbefollowedbyanunderscore(“_'')orexclamationmark(“!'')tousetheunderlyingplatform'snativesizeforthespecifiedtype;otherwise,itusesaplatform-independentconsistentsize.Spacesareignoredintheformatstring.SeealsoArray#pack.

tr!(from_str,to_str)→strornil

tr_s(from_str,to_str)→new_str

tr_s!(from_str,to_str)→strornil

unpack(format)→anArray

Page 788: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

"abc\00\\00aabc\00\\00"".unpack('A6Z6')#=>["abc","abc"]

"abc\00\\00"".unpack('a3a3')#=>["abc","\000\000"]

"abc\00aabc\00"".unpack('Z*Z*')#=>["abc","abc"]

"aa".unpack('b8B8')#=>["10000110","01100001"]

"aaa".unpack('h2H2c')#=>["16","61",97]

"\xfe\xff\xfe\xff".unpack('sS')#=>[-2,65534]

"now=20is".unpack('M*')#=>["nowis"]

"whole".unpack('xax2aX2aX1aX2a')#=>["h","e","l","l","o"]

ThistablesummarizesthevariousformatsandtheRubyclassesreturnedbyeach.

Integer||

Directive|Returns|Meaning

-----------------------------------------------------------------

C|Integer|8-bitunsigned(unsignedchar)

S|Integer|16-bitunsigned,nativeendian(uint16_t)

L|Integer|32-bitunsigned,nativeendian(uint32_t)

Q|Integer|64-bitunsigned,nativeendian(uint64_t)

||

c|Integer|8-bitsigned(signedchar)

s|Integer|16-bitsigned,nativeendian(int16_t)

l|Integer|32-bitsigned,nativeendian(int32_t)

q|Integer|64-bitsigned,nativeendian(int64_t)

||

S_,S!|Integer|unsignedshort,nativeendian

I,I_,I!|Integer|unsignedint,nativeendian

L_,L!|Integer|unsignedlong,nativeendian

Q_,Q!|Integer|unsignedlonglong,nativeendian(ArgumentError

||iftheplatformhasnolonglongtype.)

||(Q_andQ!isavailablesinceRuby2.1.)

||

s_,s!|Integer|signedshort,nativeendian

i,i_,i!|Integer|signedint,nativeendian

l_,l!|Integer|signedlong,nativeendian

q_,q!|Integer|signedlonglong,nativeendian(ArgumentError

||iftheplatformhasnolonglongtype.)

||(q_andq!isavailablesinceRuby2.1.)

||

S>L>Q>|Integer|sameasthedirectiveswithout">"except

s>l>q>||bigendian

S!>I!>||(availablesinceRuby1.9.3)

L!>Q!>||"S>"issameas"n"

s!>i!>||"L>"issameas"N"

l!>q!>||

||

Page 789: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

S<L<Q<|Integer|sameasthedirectiveswithout"<"except

s<l<q<||littleendian

S!<I!<||(availablesinceRuby1.9.3)

L!<Q!<||"S<"issameas"v"

s!<i!<||"L<"issameas"V"

l!<q!<||

||

n|Integer|16-bitunsigned,network(big-endian)byteorder

N|Integer|32-bitunsigned,network(big-endian)byteorder

v|Integer|16-bitunsigned,VAX(little-endian)byteorder

V|Integer|32-bitunsigned,VAX(little-endian)byteorder

||

U|Integer|UTF-8character

w|Integer|BER-compressedinteger(seeArray.pack)

Float||

Directive|Returns|Meaning

-----------------------------------------------------------------

D,d|Float|double-precision,nativeformat

F,f|Float|single-precision,nativeformat

E|Float|double-precision,little-endianbyteorder

e|Float|single-precision,little-endianbyteorder

G|Float|double-precision,network(big-endian)byteorder

g|Float|single-precision,network(big-endian)byteorder

String||

Directive|Returns|Meaning

-----------------------------------------------------------------

A|String|arbitrarybinarystring(removetrailingnullsandASCIIspaces)

a|String|arbitrarybinarystring

Z|String|null-terminatedstring

B|String|bitstring(MSBfirst)

b|String|bitstring(LSBfirst)

H|String|hexstring(highnibblefirst)

h|String|hexstring(lownibblefirst)

u|String|UU-encodedstring

M|String|quoted-printable,MIMEencoding(seeRFC2045)

m|String|base64encodedstring(RFC2045)(default)

||base64encodedstring(RFC4648)iffollowedby0

P|String|pointertoastructure(fixed-lengthstring)

p|String|pointertoanull-terminatedstring

Misc.||

Directive|Returns|Meaning

-----------------------------------------------------------------

@|---|skiptotheoffsetgivenbythelengthargument

X|---|skipbackwardonebyte

Page 790: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

x|---|skipforwardonebyte

Returnsacopyofstrwithalllowercaselettersreplacedwiththeiruppercasecounterparts.Theoperationislocaleinsensitive—onlycharacters“a''to“z''areaffected.Note:casereplacementiseffectiveonlyinASCIIregion.

"hEllO".upcase#=>"HELLO"

Upcasesthecontentsofstr,returningnilifnochangesweremade.Note:casereplacementiseffectiveonlyinASCIIregion.

Iteratesthroughsuccessivevalues,startingatstrandendingatother_strinclusive,passingeachvalueinturntotheblock.TheString#succmethodisusedtogenerateeachvalue.Ifoptionalsecondargumentexclusiveisomittedorisfalse,thelastvaluewillbeincluded;otherwiseitwillbeexcluded.

Ifnoblockisgiven,anenumeratorisreturnedinstead.

"a8".upto("b6"){|s|prints,''}

forsin"a8".."b6"

prints,''

end

upcase→new_str

upcase!→strornil

upto(other_str,exclusive=false){|s|block}→strupto(other_str,exclusive=false)→an_enumerator

Page 791: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

produces:

a8a9b0b1b2b3b4b5b6

a8a9b0b1b2b3b4b5b6

Ifstrandother_strcontainsonlyasciinumericcharacters,botharerecognizedasdecimalnumbers.Inaddition,thewidthofstring(e.g.leadingzeros)ishandledappropriately.

"9".upto("11").to_a#=>["9","10","11"]

"25".upto("5").to_a#=>[]

"07".upto("11").to_a#=>["07","08","09","10","11"]

Returnstrueforastringwhichencodedcorrectly.

"\xc2\xa1".force_encoding("UTF-8").valid_encoding?#=>true

"\xc2".force_encoding("UTF-8").valid_encoding?#=>false

"\x80".force_encoding("UTF-8").valid_encoding?#=>false

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

valid_encoding?→trueorfalse

Page 792: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classStruct

InFilesprocess.cstruct.c

ParentObject

IncludedModulesEnumerable

Constants

Tms

PublicClassMethods

ThefirsttwoformsareusedtocreateanewStruct

new([class_name][,member_name]+>)→StructClassnew([class_name][,member_name]+>){|StructClass|block}→StructClassnew(value,...)→objStructClass[value,...]→obj

Page 793: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

subclassclass_namethatcancontainavalueforeachmember_name.ThissubclasscanbeusedtocreateinstancesofthestructurelikeanyotherClass.

Iftheclass_nameisomittedananonymousstructureclasswillbecreated.Otherwise,thenameofthisstructwillappearasaconstantinclassStruct,soitmustbeuniqueforallStructsinthesystemandmuststartwithacapitalletter.Assigningastructureclasstoaconstantalsogivestheclassthenameoftheconstant.

#CreateastructurewithanameunderStruct

Struct.new("Customer",:name,:address)

#=>Struct::Customer

Struct::Customer.new("Dave","123Main")

#=>#<structStruct::Customername="Dave",address="123Main">

IfablockisgivenitwillbeevaluatedinthecontextofStructClass,passingthecreatedclassasaparameter:

Customer=Struct.new(:name,:address)do

defgreeting

"Hello#{name}!"

end

end

Customer.new("Dave","123Main").greeting#=>"HelloDave!"

Thisistherecommendedwaytocustomizeastruct.Subclassingananonymousstructcreatesanextraanonymousclassthatwillneverbeused.

Thelasttwoformscreateanewinstanceofastructsubclass.Thenumberofvalueparametersmustbelessthanorequaltothenumberofattributesdefinedforthestructure.Unsetparametersdefaulttonil.PassingmoreparametersthannumberofattributeswillraiseanArgumentError.

Page 794: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#Createastructurenamedbyitsconstant

Customer=Struct.new(:name,:address)

#=>Customer

Customer.new("Dave","123Main")

#=>#<structCustomername="Dave",address="123Main">

PublicInstanceMethods

Equality—Returnstrueifotherhasthesamestructsubclassandhasequalmembervalues(accordingtoObject#==).

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joejr=Customer.new("JoeSmith","123Maple,AnytownNC"

jane=Customer.new("JaneDoe","456Elm,AnytownNC"

joe==joejr#=>true

joe==jane#=>false

AttributeReference—Returnsthevalueofthegivenstructmemberorthememberatthegivenindex.RaisesNameErrorifthememberdoesnotexistandIndexErroriftheindexisoutofrange.

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe["name"]#=>"JoeSmith"

joe[:name]#=>"JoeSmith"

joe[0]#=>"JoeSmith"

struct==other→trueorfalse

struct[member]→anObjectstruct[index]→anObject

Page 795: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

AttributeAssignment—Setsthevalueofthegivenstructmemberorthememberatthegivenindex.RaisesNameErrorifthenamedoesnotexistandIndexErroriftheindexisoutofrange.

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe["name"]="Luke"

joe[:zip]="90210"

joe.name#=>"Luke"

joe.zip#=>"90210"

Yieldsthevalueofeachstructmemberinorder.Ifnoblockisgivenanenumeratorisreturned.

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.each{|x|puts(x)}

Produces:

JoeSmith

123Maple,AnytownNC

12345

Yieldsthenameandvalueofeachstructmemberinorder.Ifnoblockisgivenanenumeratorisreturned.

struct[name]=obj→objstruct[index]=obj→obj

each{|obj|block}→structeach→an_enumerator

each_pair{|sym,obj|block}→structeach_pair→an_enumerator

Page 796: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.each_pair{|name,value|puts("#{name}=>#{value}"

Produces:

name=>JoeSmith

address=>123Maple,AnytownNC

zip=>12345

Hashequality—otherandstructrefertothesamehashkeyiftheyhavethesamestructsubclassandhaveequalmembervalues(accordingtoObject#eql?).

Returnsahashvaluebasedonthisstruct'scontents(seeObject#hash).

SeealsoObject#hash.

Describethecontentsofthisstructinastring.

Alsoaliasedas:to_s

Returnsthenumberofstructmembers.

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.length#=>3

eql?(other)→trueorfalse

hash→fixnum

to_s→stringinspect→string

length→fixnumsize→fixnum

Page 797: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthestructmembersasanarrayofsymbols:

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.members#=>[:name,:address,:zip]

YieldseachmembervaluefromthestructtotheblockandreturnsanArraycontainingthemembervaluesfromthestructforwhichthegivenblockreturnsatruevalue(equivalenttoEnumerable#select).

Lots=Struct.new(:a,:b,:c,:d,:e,:f)

l=Lots.new(11,22,33,44,55,66)

l.select{|v|(v%2).zero?}#=>[22,44,66]

Returnsthenumberofstructmembers.

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.length#=>3

ReturnsthevaluesforthisstructasanArray.

Customer=Struct.new(:name,:address,:zip)

members→array

select{|i|block}→arrayselect→an_enumerator

length→fixnumsize→fixnum

to_a→arrayvalues→array

Page 798: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.to_a[1]#=>"123Maple,AnytownNC"

ReturnsaHashcontainingthenamesandvaluesforthestruct'smembers.

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.to_h[:address]#=>"123Maple,AnytownNC"

Aliasfor:inspect

ReturnsthevaluesforthisstructasanArray.

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.to_a[1]#=>"123Maple,AnytownNC"

ReturnsthestructmembervaluesforeachselectorasanArray.AselectormaybeeitheranIntegeroffsetoraRangeofoffsets(asinArray#values_at).

Customer=Struct.new(:name,:address,:zip)

joe=Customer.new("JoeSmith","123Maple,AnytownNC"

joe.values_at0,2#=>["JoeSmith",12345]

GeneratedbyRDoc3.12.2.

to_h→hash

to_s()

to_a→arrayvalues→array

values_at(selector,...)→an_array

Page 799: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedwiththeDarkfishRdocGenerator3.

Page 800: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classSymbolSymbolobjectsrepresentnamesandsomestringsinsidetheRubyinterpreter.Theyaregeneratedusingthe:nameand:"string"literalssyntax,andbythevariousto_symmethods.ThesameSymbolobjectwillbecreatedforagivennameorstringforthedurationofaprogram'sexecution,regardlessofthecontextormeaningofthatname.ThusifFredisaconstantinonecontext,amethodinanother,andaclassinathird,theSymbol:Fredwillbethesameobjectinallthreecontexts.

moduleOne

classFred

end

$f1=:Fred

end

moduleTwo

Fred=1

$f2=:Fred

end

defFred()

end

$f3=:Fred

$f1.object_id#=>2514190

$f2.object_id#=>2514190

$f3.object_id#=>2514190

InFilesstring.c

Page 801: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ParentObject

IncludedModulesComparable

PublicClassMethods

ReturnsanarrayofallthesymbolscurrentlyinRuby'ssymboltable.

Symbol.all_symbols.size#=>903

Symbol.all_symbols[1,20]#=>[:floor,:ARGV,:Binding,:symlink,

:chown,:EOFError,:$;

:LOCK_SH,:"setuid?",:

:default_proc,:compact

:Tms,:getwd,:$=,:ThreadGroup

:wait2,:$>]

PublicInstanceMethods

Comparessymbolwithother_symbolaftercallingto_soneachofthesymbols.Returns-1,0,+1ornildependingonwhethersymbolislessthan,equalto,orgreaterthanother_symbol.

+nil+isreturnedifthetwovaluesareincomparable.

SeeString#<=>formoreinformation.

all_symbols→array

symbol<=>other_symbol→-1,0,+1ornil

Page 802: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Equality—Ifsymandobjareexactlythesamesymbol,returnstrue.

Equality—Ifsymandobjareexactlythesamesymbol,returnstrue.

Returnssym.to_s=~obj.

Returnssym.to_s[].

Sameassym.to_s.capitalize.intern.

Case-insensitiveversionofSymbol#<=>.

Sameassym.to_s.downcase.intern.

Returnsthatsymis:“”ornot.

sym==obj→trueorfalse

sym==obj→trueorfalse

sym=~obj→fixnumornilmatch(obj)→fixnumornil

sym[idx]→charsym[b,n]→stringslice(idx)→charslice(b,n)→string

capitalize→symbol

casecmp(other)→-1,0,+1ornil

downcase→symbol

empty?→trueorfalse

Page 803: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstheEncodingobjectthatrepresentstheencodingofsym.

Returnsthenameorstringcorrespondingtosym.

:fred.id2name#=>"fred"

Returnstherepresentationofsymasasymbolliteral.

:fred.inspect#=>":fred"

Ingeneral,to_symreturnstheSymbolcorrespondingtoanobject.Assymisalreadyasymbol,selfisreturnedinthiscase.

Sameassym.to_s.length.

Returnssym.to_s=~obj.

encoding→encoding

id2name→stringto_s→string

inspect→string

to_sym→symintern→sym

length→integersize→integer

sym=~obj→fixnumornilmatch(obj)→fixnumornil

Page 804: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Sameassym.to_s.succ.intern.

Sameassym.to_s.length.

Returnssym.to_s[].

Sameassym.to_s.succ.intern.

Sameassym.to_s.swapcase.intern.

ReturnsaProcobjectwhichrespondtothegivenmethodbysym.

(1..3).collect(&:to_s)#=>["1","2","3"]

Returnsthenameorstringcorrespondingtosym.

:fred.id2name#=>"fred"

succ

length→integersize→integer

sym[idx]→charsym[b,n]→stringslice(idx)→charslice(b,n)→string

succ

swapcase→symbol

to_proc

id2name→stringto_s→string

Page 805: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ingeneral,to_symreturnstheSymbolcorrespondingtoanobject.Assymisalreadyasymbol,selfisreturnedinthiscase.

Sameassym.to_s.upcase.intern.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

to_sym→symintern→sym

upcase→symbol

Page 806: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classSyntaxErrorRaisedwhenencounteringRubycodewithaninvalidsyntax.

eval("1+1=2")

raisestheexception:

SyntaxError:(eval):1:syntaxerror,unexpected'=',expecting$end

InFileserror.c

ParentScriptError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 807: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classSystemCallErrorSystemCallErroristhebaseclassforalllow-levelplatform-dependenterrors.

TheerrorsavailableonthecurrentplatformaresubclassesofSystemCallErrorandaredefinedintheErrnomodule.

File.open("does/not/exist")

raisestheexception:

Errno::ENOENT:Nosuchfileordirectory-does/not/exist

InFileserror.c

ParentStandardError

PublicClassMethods

ReturntrueifthereceiverisagenericSystemCallError,oriftheerrornumbersselfand

system_call_error===other→trueorfalse

Page 808: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

otherarethesame.

Iferrnocorrespondstoaknownsystemerrorcode,constructstheappropriateErrnoclassforthaterror,otherwiseconstructsagenericSystemCallErrorobject.Theerrornumberissubsequentlyavailableviatheerrnomethod.

PublicInstanceMethods

ReturnthisSystemCallError'serrornumber.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

new(msg,errno)→system_call_error_subclass

errno→fixnum

Page 809: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classSystemExitRaisedbyexittoinitiatetheterminationofthescript.

InFileserror.c

ParentException

PublicClassMethods

CreateanewSystemExitexceptionwiththegivenstatusandmessage.Statusistrue,false,oraninteger.Ifstatusisnotgiven,trueisused.

PublicInstanceMethods

Returnthestatusvalueassociatedwiththissystemexit.

new→system_exitnew(status)→system_exitnew(status,msg)→system_exitnew(msg)→system_exit

status→fixnum

Page 810: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifexitingsuccessful,falseifnot.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

success?→trueorfalse

Page 811: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classSystemStackErrorRaisedincaseofastackoverflow.

defme_myself_and_i

me_myself_and_i

end

me_myself_and_i

raisestheexception:

SystemStackError:stackleveltoodeep

InFilesproc.c

ParentException

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 812: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classThreadThreadsaretheRubyimplementationforaconcurrentprogrammingmodel.

ProgramsthatrequiremultiplethreadsofexecutionareaperfectcandidateforRuby'sThreadclass.

Forexample,wecancreateanewthreadseparatefromthemainthread'sexecutionusing::new.

thr=Thread.new{puts"Whatsthebigdeal"}

Thenweareabletopausetheexecutionofthemainthreadandallowournewthreadtofinish,usingjoin:

thr.join#=>"Whatsthebigdeal"

Ifwedon'tcallthr.joinbeforethemainthreadterminates,thenallotherthreadsincludingthrwillbekilled.

Alternatively,youcanuseanarrayforhandlingmultiplethreadsatonce,likeinthefollowingexample:

threads=[]

Page 813: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

threads<<Thread.new{puts"Whatsthebigdeal"}

threads<<Thread.new{3.times{puts"Threadsarefun!"}}

Aftercreatingafewthreadswewaitforthemalltofinishconsecutively.

threads.each{|thr|thr.join}

Threadinitialization

Inordertocreatenewthreads,Rubyprovides::new,::start,and::fork.Ablockmustbeprovidedwitheachofthesemethods,otherwiseaThreadErrorwillberaised.

WhensubclassingtheThreadclass,theinitializemethodofyoursubclasswillbeignoredby::startand::fork.Otherwise,besuretocallsuperinyourinitializemethod.

Threadtermination

Forterminatingthreads,Rubyprovidesavarietyofwaystodothis.

Theclassmethod::kill,ismeanttoexitagiventhread:

thr=Thread.new{...}

Thread.kill(thr)#sendsexit()tothr

Alternatively,youcanusetheinstancemethod

Page 814: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

exit,oranyofitsaliaseskillorterminate.

thr.exit

Threadstatus

Rubyprovidesafewinstancemethodsforqueryingthestateofagiventhread.Togetastringwiththecurrentthread'sstateusestatus

thr=Thread.new{sleep}

thr.status#=>"sleep"

thr.exit

thr.status#=>false

Youcanalsousealive?totellifthethreadisrunningorsleeping,andstop?ifthethreadisdeadorsleeping.

Threadvariablesandscope

Sincethreadsarecreatedwithblocks,thesamerulesapplytootherRubyblocksforvariablescope.Anylocalvariablescreatedwithinthisblockareaccessibletoonlythisthread.

Fiber-localvs.Thread-local

EachfiberhasitsownbucketforThread#[]storage.Whenyousetanewfiber-localitisonlyaccessiblewithinthisFiber.Toillustrate:

Thread.new{

Page 815: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thread.current[:foo]="bar"

Fiber.new{

pThread.current[:foo]#=>nil

}.resume

}.join

Thisexampleuses#[]forgettingand#[]=forsettingfiber-locals,youcanalsousekeystolistthefiber-localsforagiventhreadandkey?tocheckifafiber-localexists.

Whenitcomestothread-locals,theyareaccessiblewithintheentirescopeofthethread.Giventhefollowingexample:

Thread.new{

Thread.current.thread_variable_set(:foo,1)

pThread.current.thread_variable_get(:foo)#=>1

Fiber.new{

Thread.current.thread_variable_set(:foo,2)

pThread.current.thread_variable_get(:foo)#=>2

}.resume

pThread.current.thread_variable_get(:foo)#=>2

}.join

Youcanseethatthethread-local:foocarriedoverintothefiberandwaschangedto2bytheendofthethread.

Thisexamplemakesuseofthread_variable_settocreatenewthread-locals,andthread_variable_gettoreferencethem.

Thereisalsothread_variablestolistallthread-locals,andthread_variable?tocheckifagiven

Page 816: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

thread-localexists.

Exceptionhandling

Anythreadcanraiseanexceptionusingtheraiseinstancemethod,whichoperatessimilarlytoKernel#raise.

However,it'simportanttonotethatanexceptionthatoccursinanythreadexceptthemainthreaddependsonabort_on_exception.Thisoptionisfalsebydefault,meaningthatanyunhandledexceptionwillcausethethreadtoterminatesilentlywhenwaitedonbyeitherjoinorvalue.Youcanchangethisdefaultbyeitherabort_on_exception=trueorsetting$::DEBUGtotrue.

Withtheadditionoftheclassmethod::handle_interrupt,youcannowhandleexceptionsasynchronouslywiththreads.

Scheduling

Rubyprovidesafewwaystosupportschedulingthreadsinyourprogram.

Thefirstwayisbyusingtheclassmethod::stop,toputthecurrentrunningthreadtosleepandscheduletheexecutionofanotherthread.

Onceathreadisasleep,youcanusetheinstancemethodwakeuptomarkyourthreadas

Page 817: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

eligibleforscheduling.

Youcanalsotry::pass,whichattemptstopassexecutiontoanotherthreadbutisdependentontheOSwhetherarunningthreadwillswitchornot.Thesamegoesforpriority,whichletsyouhinttothethreadschedulerwhichthreadsyouwanttotakeprecedencewhenpassingexecution.ThismethodisalsodependentontheOSandmaybeignoredonsomeplatforms.

InFilesthread.cvm.cvm_trace.c

ParentObject

PublicClassMethods

Returnsthethreaddebuglevel.AvailableonlyifcompiledwithTHREAD_DEBUG=-1.

Setsthethreaddebuglevel.AvailableonlyifcompiledwithTHREAD_DEBUG=-1.

DEBUG→num

DEBUG=num

Page 818: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthestatusoftheglobal“abortonexception''condition.

Thedefaultisfalse.

Whensettotrue,allthreadswillabort(theprocesswillexit(0))ifanexceptionisraisedinanythread.

Canalsobespecifiedbytheglobal$::DEBUGflagorcommandlineoption-d.

Seealso::abort_on_exception=.

Thereisalsoaninstancelevelmethodtosetthisforaspecificthread,seeabort_on_exception.

Whensettotrue,allthreadswillabortifanexceptionisraised.Returnsthenewstate.

Thread.abort_on_exception=true

t1=Thread.newdo

puts"Innewthread"

raise"Exceptionfromthread"

end

sleep(1)

puts"notreached"

Thiswillproduce:

Innewthread

prog.rb:4:Exceptionfromthread(RuntimeError)

fromprog.rb:2:in`initialize'

fromprog.rb:2:in`new'

fromprog.rb:2

Seealso::abort_on_exception.

Thereisalsoaninstancelevelmethodtosetthisforaspecificthread,seeabort_on_exception=.

abort_on_exception→trueorfalse

abort_on_exception=boolean→trueorfalse

Page 819: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthecurrentlyexecutingthread.

Thread.current#=>#<Thread:0x401bdf4crun>

Terminatesthecurrentlyrunningthreadandschedulesanotherthreadtoberun.

Ifthisthreadisalreadymarkedtobekilled,::exitreturnstheThread.

Ifthisisthemainthread,orthelastthread,exittheprocess.

Basicallythesameas::new.However,ifclassThreadissubclassed,thencallingstartinthatsubclasswillnotinvokethesubclass'sinitializemethod.

Changesasynchronousinterrupttiming.

interruptmeansasynchronouseventandcorrespondingprocedureby#raise,#kill,signaltrap(notsupportedyet)andmainthreadtermination(ifmainthreadterminates,thenallotherthreadwillbekilled).

ThegivenhashhaspairslikeExceptionClass=>:TimingSymbol.WheretheExceptionClassisthe

current→thread

exit→thread

start([args]*){|args|block}→threadfork([args]*){|args|block}→thread

handle_interrupt(hash){...}→resultoftheblock

Page 820: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

interrupthandledbythegivenblock.TheTimingSymbolcanbeoneofthefollowingsymbols:

:immediate

Invokeinterruptsimmediately.

:on_blocking

InvokeinterruptswhileBlockingOperation.

:never

Neverinvokeallinterrupts.

BlockingOperationmeansthattheoperationwillblockthecallingthread,suchasreadandwrite.OnCRubyimplementation,BlockingOperationisanyoperationexecutedwithoutGVL.

Maskedasynchronousinterruptsaredelayeduntiltheyareenabled.Thismethodissimilartosigprocmask(3).

NOTEAsynchronousinterruptsaredifficulttouse.

Ifyouneedtocommunicatebetweenthreads,pleaseconsidertouseanotherwaysuchasQueue.

Orusethemwithdeepunderstandingaboutthismethod.

UsageInthisexample,wecanguardfrom#raiseexceptions.

Usingthe:neverTimingSymboltheRuntimeErrorexceptionwillalwaysbeignoredinthefirstblockofthemainthread.Inthesecond::handle_interruptblockwecanpurposefullyhandleRuntimeErrorexceptions.

Page 821: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

th=Thread.newdo

Thread.handle_interrupt(RuntimeError=>:never){

begin

#Youcanwriteresourceallocationcodesafely.

Thread.handle_interrupt(RuntimeError=>:immediate

#...

}

ensure

#Youcanwriteresourcedeallocationcodesafely.

end

}

end

Thread.pass

#...

th.raise"stop"

WhileweareignoringtheRuntimeErrorexception,it'ssafetowriteourresourceallocationcode.Then,theensureblockiswherewecansafelydeallocateyourresources.

GuardingfromTimeout::ErrorInthenextexample,wewillguardfromtheTimeout::Errorexception.ThiswillhelppreventfromleakingresourceswhenTimeout::Errorexceptionsoccurduringnormalensureclause.ForthisexampleweusethehelpofthestandardlibraryTimeout,fromlib/timeout.rb

require'timeout'

Thread.handle_interrupt(Timeout::Error=>:never){

timeout(10){

#Timeout::Errordoesn'toccurhere

Thread.handle_interrupt(Timeout::Error=>:on_blocking

#possibletobekilledbyTimeout::Error

#whileblockingoperation

}

#Timeout::Errordoesn'toccurhere

}

}

Page 822: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Inthefirstpartofthetimeoutblock,wecanrelyonTimeout::Errorbeingignored.ThenintheTimeout::Error=>:on_blockingblock,anyoperationthatwillblockthecallingthreadissusceptibletoaTimeout::Errorexceptionbeingraised.

StackcontrolsettingsIt'spossibletostackmultiplelevelsof::handle_interruptblocksinordertocontrolmorethanoneExceptionClassandTimingSymbolatatime.

Thread.handle_interrupt(FooError=>:never){

Thread.handle_interrupt(BarError=>:never){

#FooErrorandBarErrorareprohibited.

}

}

InheritancewithExceptionClassAllexceptionsinheritedfromtheExceptionClassparameterwillbeconsidered.

Thread.handle_interrupt(Exception=>:never){

#allexceptionsinheritedfromExceptionareprohibited.

}

Causesthegiventhreadtoexit,seealso::exit.

count=0

a=Thread.new{loop{count+=1}}

sleep(0.1)#=>0

Thread.kill(a)#=>#<Thread:0x401b3d30dead>

count#=>93947

a.alive?#=>false

kill(thread)→thread

list→array

Page 823: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsanarrayofThreadobjectsforallthreadsthatareeitherrunnableorstopped.

Thread.new{sleep(200)}

Thread.new{1000000.times{|i|i*i}}

Thread.new{Thread.stop}

Thread.list.each{|t|pt}

Thiswillproduce:

#<Thread:0x401b3e84sleep>

#<Thread:0x401b3f38run>

#<Thread:0x401b3fb0sleep>

#<Thread:0x401bdf4crun>

Returnsthemainthread.

Createsanewthreadexecutingthegivenblock.

Anyargsgivento::newwillbepassedtotheblock:

arr=[]

a,b,c=1,2,3

Thread.new(a,b,c){|d,e,f|arr<<d<<e<<f}.join

arr#=>[1,2,3]

AThreadErrorexceptionisraisedif::newiscalledwithoutablock.

Ifyou'regoingtosubclassThread,besuretocallsuperinyourinitializemethod,otherwiseaThreadErrorwillberaised.

main→thread

new{...}→threadnew(*args,&proc)→threadnew(*args){|args|...}→thread

pass→nil

Page 824: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Givethethreadschedulerahinttopassexecutiontoanotherthread.Arunningthreadmayormaynotswitch,itdependsonOSandprocessor.

Returnswhetherornottheasynchronousqueueisempty.

Since::handle_interruptcanbeusedtodeferasynchronousevents,thismethodcanbeusedtodetermineifthereareanydeferredevents.

Ifyoufindthismethodreturnstrue,thenyoumayfinish:neverblocks.

Forexample,thefollowingmethodprocessesdeferredasynchronouseventsimmediately.

defThread.kick_interrupt_immediately

Thread.handle_interrupt(Object=>:immediate){

Thread.pass

}

end

Iferrorisgiven,thencheckonlyforerrortypedeferredevents.

Usageth=Thread.new{

Thread.handle_interrupt(RuntimeError=>:on_blocking

whiletrue

...

#reachsafepointtoinvokeinterrupt

ifThread.pending_interrupt?

Thread.handle_interrupt(Object=>:immediate){}

end

...

end

}

}

pending_interrupt?(error=nil)→true/false

Page 825: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

...

th.raise#stopthread

Thisexamplecanalsobewrittenasthefollowing,whichyoushouldusetoavoidasynchronousinterrupts.

flag=true

th=Thread.new{

Thread.handle_interrupt(RuntimeError=>:on_blocking

whiletrue

...

#reachsafepointtoinvokeinterrupt

breakifflag==false

...

end

}

}

...

flag=false#stopthread

Basicallythesameas::new.However,ifclassThreadissubclassed,thencallingstartinthatsubclasswillnotinvokethesubclass'sinitializemethod.

Stopsexecutionofthecurrentthread,puttingitintoa“sleep''state,andschedulesexecutionofanotherthread.

a=Thread.new{print"a";Thread.stop;print"c"}

sleep0.1whilea.status!='sleep'

print"b"

a.run

a.join

start([args]*){|args|block}→threadfork([args]*){|args|block}→thread

stop→nil

Page 826: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#=>"abc"

PublicInstanceMethods

AttributeReference—Returnsthevalueofafiber-localvariable(currentthread'srootfiberifnotexplicitlyinsideaFiber),usingeitherasymbolorastringname.Ifthespecifiedvariabledoesnotexist,returnsnil.

[

Thread.new{Thread.current["name"]="A"},

Thread.new{Thread.current[:name]="B"},

Thread.new{Thread.current["name"]="C"}

].eachdo|th|

th.join

puts"#{th.inspect}:#{th[:name]}"

end

Thiswillproduce:

#<Thread:0x00000002a54220dead>:A

#<Thread:0x00000002a541a8dead>:B

#<Thread:0x00000002a54130dead>:C

Thread#[]andThread#[]=arenotthread-localbutfiber-local.ThisconfusiondidnotexistinRuby1.8becausefibersareonlyavailablesinceRuby1.9.Ruby1.9choosesthatthemethodsbehavesfiber-localtosavefollowingidiomfordynamicscope.

defmeth(newvalue)

begin

oldvalue=Thread.current[:name]

Thread.current[:name]=newvalue

yield

ensure

Thread.current[:name]=oldvalue

thr[sym]→objornil

Page 827: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

end

Theidiommaynotworkasdynamicscopeifthemethodsarethread-localandagivenblockswitchesfiber.

f=Fiber.new{

meth(1){

Fiber.yield

}

}

meth(2){

f.resume

}

f.resume

pThread.current[:name]

#=>niliffiber-local

#=>2ifthread-local(Thevalue2isleakedtooutsideofmethmethod.)

Forthread-localvariables,pleaseseethread_variable_getandthread_variable_set.

AttributeAssignment—Setsorcreatesthevalueofafiber-localvariable,usingeitherasymbolorastring.

SeealsoThread#[].

Forthread-localvariables,pleaseseethread_variable_setandthread_variable_get.

Returnsthestatusofthethread-local“abortonexception''conditionforthisthr.

Thedefaultisfalse.

Seealsoabort_on_exception=.

Thereisalsoaclasslevelmethodtosetthisforall

thr[sym]=obj→obj

abort_on_exception→trueorfalse

Page 828: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

threads,see::abort_on_exception.

Whensettotrue,allthreads(includingthemainprogram)willabortifanexceptionisraisedinthisthr.

Theprocesswilleffectivelyexit(0).

Seealsoabort_on_exception.

Thereisalsoaclasslevelmethodtosetthisforallthreads,see::abort_on_exception=.

Addsprocasahandlerfortracing.

See#set_trace_funcandKernel#set_trace_func.

Returnstrueifthrisrunningorsleeping.

thr=Thread.new{}

thr.join#=>#<Thread:0x401b3fb0dead>

Thread.current.alive?#=>true

thr.alive?#=>false

Seealsostop?andstatus.

Returnsthecurrentbacktraceofthetargetthread.

Returnstheexecutionstackforthetargetthread—an

abort_on_exception=boolean→trueorfalse

add_trace_func(proc)→proc

alive?→trueorfalse

backtrace→array

backtrace_locations(*args)→arrayornil

Page 829: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

arraycontainingbacktracelocationobjects.

SeeThread::Backtrace::Locationformoreinformation.

ThismethodbehavessimilarlytoKernel#caller_locationsexceptitappliestoaspecificthread.

Terminatesthrandschedulesanotherthreadtoberun.

Ifthisthreadisalreadymarkedtobekilled,exitreturnstheThread.

Ifthisisthemainthread,orthelastthread,exitstheprocess.

ReturnstheThreadGroupwhichcontainsthegiventhread,orreturnsnilifthrisnotamemberofanygroup.

Thread.main.group#=>#<ThreadGroup:0x4029d914>

Dumpthename,id,andstatusofthrtoastring.

Thecallingthreadwillsuspendexecutionandrunthis

exit→thrornilkill→thrornilterminate→thrornil

group→thgrpornil

inspect→string

join→thrjoin(limit)→thr

Page 830: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

thr.

Doesnotreturnuntilthrexitsoruntilthegivenlimitsecondshavepassed.

Ifthetimelimitexpires,nilwillbereturned,otherwisethrisreturned.

Anythreadsnotjoinedwillbekilledwhenthemainprogramexits.

Ifthrhadpreviouslyraisedanexceptionandthe::abort_on_exceptionor$::DEBUGflagsarenotset,(sotheexceptionhasnotyetbeenprocessed),itwillbeprocessedatthistime.

a=Thread.new{print"a";sleep(10);print"b";print

x=Thread.new{print"x";Thread.pass;print"y";print

x.join#Letthreadxfinish,threadawillbekilledonexit.

#=>"axyz"

Thefollowingexampleillustratesthelimitparameter.

y=Thread.new{4.times{sleep0.1;puts'tick...'}}

puts"Waiting"untily.join(0.15)

Thiswillproduce:

tick...

Waiting

tick...

Waiting

tick...

tick...

Returnstrueifthegivenstring(orsymbol)existsasafiber-localvariable.

key?(sym)→trueorfalse

Page 831: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

me=Thread.current

me[:oliver]="a"

me.key?(:oliver)#=>true

me.key?(:stanley)#=>false

Returnsanarrayofthenamesofthefiber-localvariables(asSymbols).

thr=Thread.newdo

Thread.current[:cat]='meow'

Thread.current["dog"]='woof'

end

thr.join#=>#<Thread:0x401b3f10dead>

thr.keys#=>[:dog,:cat]

Terminatesthrandschedulesanotherthreadtoberun.

Ifthisthreadisalreadymarkedtobekilled,exitreturnstheThread.

Ifthisisthemainthread,orthelastthread,exitstheprocess.

Returnswhetherornottheasynchronousqueueisemptyforthetargetthread.

Iferrorisgiven,thencheckonlyforerrortypedeferredevents.

See::pending_interrupt?formoreinformation.

keys→array

exit→thrornilkill→thrornilterminate→thrornil

pending_interrupt?(error=nil)→true/false

Page 832: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthepriorityofthr.Defaultisinheritedfromthecurrentthreadwhichcreatingthenewthread,orzerofortheinitialmainthread;higher-prioritythreadwillrunmorefrequentlythanlower-prioritythreads(butlower-prioritythreadscanalsorun).

ThisisjusthintforRubythreadscheduler.Itmaybeignoredonsomeplatform.

Thread.current.priority#=>0

Setsthepriorityofthrtointeger.Higher-prioritythreadswillrunmorefrequentlythanlower-prioritythreads(butlower-prioritythreadscanalsorun).

ThisisjusthintforRubythreadscheduler.Itmaybeignoredonsomeplatform.

count1=count2=0

a=Thread.newdo

loop{count1+=1}

end

a.priority=-1

b=Thread.newdo

loop{count2+=1}

end

b.priority=-2

sleep1#=>1

count1#=>622504

count2#=>5832

Raisesanexceptionfromthegiventhread.Thecaller

priority→integer

priority=integer→thr

raiseraise(string)raise(exception[,string[,array]])

Page 833: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

doesnothavetobethr.SeeKernel#raiseformoreinformation.

Thread.abort_on_exception=true

a=Thread.new{sleep(200)}

a.raise("Gotcha")

Thiswillproduce:

prog.rb:3:Gotcha(RuntimeError)

fromprog.rb:2:in`initialize'

fromprog.rb:2:in`new'

fromprog.rb:2

Wakesupthr,makingiteligibleforscheduling.

a=Thread.new{puts"a";Thread.stop;puts"c"}

sleep0.1whilea.status!='sleep'

puts"Gothere"

a.run

a.join

Thiswillproduce:

a

Gothere

c

Seealsotheinstancemethodwakeup.

Returnsthesafelevelineffectforthr.Settingthread-localsafelevelscanhelpwhenimplementingsandboxeswhichruninsecurecode.

thr=Thread.new{$SAFE=3;sleep}

Thread.current.safe_level#=>0

thr.safe_level#=>3

run→thr

safe_level→integer

Page 834: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Establishesproconthrasthehandlerfortracing,ordisablestracingiftheparameterisnil.

SeeKernel#set_trace_func.

Returnsthestatusofthr.

"sleep"

ReturnedifthisthreadissleepingorwaitingonI/O

"run"

Whenthisthreadisexecuting

"aborting"

Ifthisthreadisaborting

false

Whenthisthreadisterminatednormally

nil

Ifterminatedwithanexception.

a=Thread.new{raise("dienow")}

b=Thread.new{Thread.stop}

c=Thread.new{Thread.exit}

d=Thread.new{sleep}

d.kill#=>#<Thread:0x401b3678aborting>

a.status#=>nil

b.status#=>"sleep"

c.status#=>false

d.status#=>"aborting"

Thread.current.status#=>"run"

set_trace_func(proc)→procset_trace_func(nil)→nil

status→string,falseornil

Page 835: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Seealsotheinstancemethodsalive?andstop?

Returnstrueifthrisdeadorsleeping.

a=Thread.new{Thread.stop}

b=Thread.current

a.stop?#=>true

b.stop?#=>false

Seealsoalive?andstatus.

Terminatesthrandschedulesanotherthreadtoberun.

Ifthisthreadisalreadymarkedtobekilled,exitreturnstheThread.

Ifthisisthemainthread,orthelastthread,exitstheprocess.

Returnstrueifthegivenstring(orsymbol)existsasathread-localvariable.

me=Thread.current

me.thread_variable_set(:oliver,"a")

me.thread_variable?(:oliver)#=>true

me.thread_variable?(:stanley)#=>false

Notethatthesearenotfiberlocalvariables.PleaseseeThread#[]and#thread_variable_getformoredetails.

stop?→trueorfalse

exit→thrornilkill→thrornilterminate→thrornil

thread_variable?(key)→trueorfalse

Page 836: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsthevalueofathreadlocalvariablethathasbeenset.Notethatthesearedifferentthanfiberlocalvalues.Forfiberlocalvalues,pleaseseeThread#[]andThread#[]=.

Threadlocalvaluesarecarriedalongwiththreads,anddonotrespectfibers.Forexample:

Thread.new{

Thread.current.thread_variable_set("foo","bar")#setathreadlocal

Thread.current["foo"]="bar"#setafiberlocal

Fiber.new{

Fiber.yield[

Thread.current.thread_variable_get("foo"),#getthethreadlocal

Thread.current["foo"],#getthefiberlocal

]

}.resume

}.join.value#=>['bar',nil]

Thevalue“bar”isreturnedforthethreadlocal,wherenilisreturnedforthefiberlocal.Thefiberisexecutedinthesamethread,sothethreadlocalvaluesareavailable.

Setsathreadlocalwithkeytovalue.Notethatthesearelocaltothreads,andnottofibers.Pleasesee#thread_variable_getandThread#[]formoreinformation.

Returnsanarrayofthenamesofthethread-localvariables(asSymbols).

thr=Thread.newdo

Thread.current.thread_variable_set(:cat,'meow')

thread_variable_get(key)→objornil

thread_variable_set(key,value)

thread_variables→array

Page 837: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thread.current.thread_variable_set("dog",'woof')

end

thr.join#=>#<Thread:0x401b3f10dead>

thr.thread_variables#=>[:dog,:cat]

Notethatthesearenotfiberlocalvariables.PleaseseeThread#[]and#thread_variable_getformoredetails.

Waitsforthrtocomplete,usingjoin,andreturnsitsvalueorraisestheexceptionwhichterminatedthethread.

a=Thread.new{2+2}

a.value#=>4

b=Thread.new{raise'somethingwentwrong'}

b.value#=>RuntimeError:somethingwentwrong

Marksagiventhreadaseligibleforscheduling,howeveritmaystillremainblockedonI/O.

Note:Thisdoesnotinvokethescheduler,seerunformoreinformation.

c=Thread.new{Thread.stop;puts"hey!"}

sleep0.1whilec.status!='sleep'

c.wakeup

c.join

#=>"hey!"

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

value→obj

wakeup→thr

Page 838: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classThreadErrorRaisedwhenaninvalidoperationisattemptedonathread.

Forexample,whennootherthreadhasbeenstarted:

Thread.stop

Thiswillraisesthefollowingexception:

ThreadError:stoppingonlythread

note:usesleeptostopforever

InFilesthread.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 839: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classThreadGroupThreadGroupprovidesameansofkeepingtrackofanumberofthreadsasagroup.

AgivenThreadobjectcanonlybelongtooneThreadGroupatatime;addingathreadtoanewgroupwillremoveitfromanypreviousgroup.

Newlycreatedthreadsbelongtothesamegroupasthethreadfromwhichtheywerecreated.

InFilesthread.c

ParentObject

Constants

Default

ThedefaultThreadGroupcreatedwhenRubystarts;allThreadsbelongtoitbydefault.

PublicInstanceMethods

Page 840: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Addsthegiventhreadtothisgroup,removingitfromanyothergrouptowhichitmayhavepreviouslybeenamember.

puts"Initialgroupis#{ThreadGroup::Default.list}"

tg=ThreadGroup.new

t1=Thread.new{sleep}

t2=Thread.new{sleep}

puts"t1is#{t1}"

puts"t2is#{t2}"

tg.add(t1)

puts"Initialgroupnow#{ThreadGroup::Default.list}"

puts"tggroupnow#{tg.list}"

Thiswillproduce:

Initialgroupis#<Thread:0x401bdf4c>

t1is#<Thread:0x401b3c90>

t2is#<Thread:0x401b3c18>

Initialgroupnow#<Thread:0x401b3c18>#<Thread:0x401bdf4c>

tggroupnow#<Thread:0x401b3c90>

PreventsthreadsfrombeingaddedtoorremovedfromthereceivingThreadGroup.

NewthreadscanstillbestartedinanenclosedThreadGroup.

ThreadGroup::Default.enclose#=>#<ThreadGroup:0x4029d914>

thr=Thread::new{Thread.stop}#=>#<Thread:0x402a7210sleep>

tg=ThreadGroup::new#=>#<ThreadGroup:0x402752d4>

tg.addthr

#=>ThreadError:can'tmovefromtheenclosedthreadgroup

add(thread)→thgrp

enclose→thgrp

enclosed?→trueorfalse

Page 841: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnstrueifthethgrpisenclosed.Seealso#enclose.

ReturnsanarrayofallexistingThreadobjectsthatbelongtothisgroup.

ThreadGroup::Default.list#=>[#<Thread:0x401bdf4crun>]

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

list→array

Page 842: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classTimeTimeisanabstractionofdatesandtimes.TimeisstoredinternallyasthenumberofsecondswithfractionsincetheEpoch,January1,197000:00UTC.AlsoseethelibrarymoduleDate.TheTimeclasstreatsGMT(GreenwichMeanTime)andUTC(CoordinatedUniversalTime)asequivalent.GMTistheolderwayofreferringtothesebaselinetimesbutpersistsinthenamesofcallsonPOSIXsystems.

Alltimesmayhavefraction.Beawareofthisfactwhencomparingtimeswitheachother–timesthatareapparentlyequalwhendisplayedmaybedifferentwhencompared.

SinceRuby1.9.2,Timeimplementationusesasigned63bitinteger,BignumorRational.TheintegerisanumberofnanosecondssincetheEpochwhichcanrepresent1823-11-12to2116-02-20.WhenBignumorRationalisused(before1823,after2116,undernanosecond),Timeworkssloweraswhenintegerisused.

Page 843: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ExamplesAlloftheseexamplesweredoneusingtheESTtimezonewhichisGMT-5.

Page 844: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CreatinganewTimeinstance

YoucancreateanewinstanceofTimewith::new.Thiswillusethecurrentsystemtime.::nowisanaliasforthis.Youcanalsopasspartsofthetimeto::newsuchasyear,month,minute,etc.Whenyouwanttoconstructatimethiswayyoumustpassatleastayear.IfyoupasstheyearwithnothingelsetimewilldefaulttoJanuary1ofthatyearat00:00:00withthecurrentsystemtimezone.Herearesomeexamples:

Time.new(2002)#=>2002-01-0100:00:00-0500

Time.new(2002,10)#=>2002-10-0100:00:00-0500

Time.new(2002,10,31)#=>2002-10-3100:00:00-0500

Time.new(2002,10,31,2,2,2,"+02:00")#=>2002-10-3102:02:02+0200

Youcanalsousegm,localandutctoinferGMT,localandUTCtimezonesinsteadofusingthecurrentsystemsetting.

Youcanalsocreateanewtimeusing::atwhichtakesthenumberofseconds(orfractionofseconds)sincetheUnixEpoch.

Time.at(628232400)#=>1989-11-2800:00:00-0500

Page 845: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

WorkingwithaninstanceofTime

OnceyouhaveaninstanceofTimethereisamultitudeofthingsyoucandowithit.Belowaresomeexamples.Forallofthefollowingexamples,wewillworkontheassumptionthatyouhavedonethefollowing:

t=Time.new(1993,02,24,12,0,0,"+09:00")

Wasthatamonday?

t.monday?#=>false

Whatyearwasthatagain?

t.year#=>1993

Wasisdaylightsavingsatthetime?

t.dst?#=>false

What'sthedayayearlater?

t+(60*60*24*365)#=>1994-02-2412:00:00+0900

HowmanysecondswasthatsincetheUnixEpoch?

Page 846: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

t.to_i#=>730522800

Youcanalsodostandardfunctionslikecomparetwotimes.

t1=Time.new(2010)

t2=Time.new(2011)

t1==t2#=>false

t1==t1#=>true

t1<t2#=>true

t1>t2#=>false

Time.new(2010,10,31).between?(t1,t2)#=>true

InFilestime.c

ParentObject

IncludedModulesComparable

PublicClassMethods

at(time)→timeat(seconds_with_frac)→timeat(seconds,microseconds_with_frac)→

Page 847: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CreatesanewTimeobjectwiththevaluegivenbytime,thegivennumberofseconds_with_frac,orsecondsandmicroseconds_with_fracsincetheEpoch.seconds_with_fracandmicroseconds_with_fraccanbeanInteger,Float,Rational,orotherNumeric.non-portablefeatureallowstheoffsettobenegativeonsomesystems.

Ifanumericargumentisgiven,theresultisinlocaltime.

Time.at(0)#=>1969-12-3118:00:00-0600

Time.at(Time.at(0))#=>1969-12-3118:00:00-0600

Time.at(946702800)#=>1999-12-3123:00:00-0600

Time.at(-284061600)#=>1960-12-3100:00:00-0600

Time.at(946684800.2).usec#=>200000

Time.at(946684800,123456.789).nsec#=>123456789

time

utc(year)→timeutc(year,month)→timeutc(year,month,day)→timeutc(year,month,day,hour)→timeutc(year,month,day,hour,min)→timeutc(year,month,day,hour,min,sec_with_frac)→timeutc(year,month,day,hour,min,sec,usec_with_frac)→timeutc(sec,min,hour,day,month,year,dummy,dummy,dummy,dummy)→timegm(year)→timegm(year,month)→timegm(year,month,day)→timegm(year,month,day,hour)→time

Page 848: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CreatesaTimeobjectbasedongivenvalues,interpretedasUTC(GMT).Theyearmustbespecified.Othervaluesdefaulttotheminimumvalueforthatfield(andmaybeniloromitted).Monthsmaybespecifiedbynumbersfrom1to12,orbythethree-letterEnglishmonthnames.Hoursarespecifiedona24-hourclock(0..23).RaisesanArgumentErrorifanyvaluesareoutofrange.Willalsoaccepttenargumentsintheorderoutputby#to_a.

sec_with_fracandusec_with_fraccanhaveafractionalpart.

Time.utc(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01UTC

Time.gm(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01UTC

gm(year,month,day,hour,min)→timegm(year,month,day,hour,min,sec_with_frac)→timegm(year,month,day,hour,min,sec,usec_with_frac)→timegm(sec,min,hour,day,month,year,dummy,dummy,dummy,dummy)→time

local(year)→timelocal(year,month)→timelocal(year,month,day)→timelocal(year,month,day,hour)→timelocal(year,month,day,hour,min)→timelocal(year,month,day,hour,min,sec_with_frac)→timelocal(year,month,day,hour,min,sec,usec_with_frac)→time

Page 849: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Sameas::gm,butinterpretsthevaluesinthelocaltimezone.

Time.local(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01-0600

local(sec,min,hour,day,month,year,dummy,dummy,isdst,dummy)→timemktime(year)→timemktime(year,month)→timemktime(year,month,day)→timemktime(year,month,day,hour)→timemktime(year,month,day,hour,min)→timemktime(year,month,day,hour,min,sec_with_frac)→timemktime(year,month,day,hour,min,sec,usec_with_frac)→timemktime(sec,min,hour,day,month,year,dummy,dummy,isdst,dummy)→time

local(year)→timelocal(year,month)→timelocal(year,month,day)→timelocal(year,month,day,hour)→timelocal(year,month,day,hour,min)→timelocal(year,month,day,hour,min,sec_with_frac)→timelocal(year,month,day,hour,min,sec,usec_with_frac)→timelocal(sec,min,hour,day,month,year,dummy,dummy,isdst,dummy)→timemktime(year)→timemktime(year,month)→time

Page 850: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Sameas::gm,butinterpretsthevaluesinthelocaltimezone.

Time.local(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01-0600

ReturnsaTimeobject.

Itisinitializedtothecurrentsystemtimeifnoargumentisgiven.

Note:Thenewobjectwillusetheresolutionavailableonyoursystemclock,andmayincludefractionalseconds.

Ifoneormoreargumentsspecified,thetimeisinitializedtothespecifiedtime.

secmayhavefractionifitisarational.

utc_offsetistheoffsetfromUTC.Itcanbeastringsuchas“+09:00”oranumberofsecondssuchas32400.

a=Time.new#=>2007-11-1907:50:02-0600

b=Time.new#=>2007-11-1907:50:02-0600

mktime(year,month,day)→timemktime(year,month,day,hour)→timemktime(year,month,day,hour,min)→timemktime(year,month,day,hour,min,sec_with_frac)→timemktime(year,month,day,hour,min,sec,usec_with_frac)→timemktime(sec,min,hour,day,month,year,dummy,dummy,isdst,dummy)→time

new→timenew(year,month=nil,day=nil,hour=nil,min=nil,sec=nil,utc_offset=nil)→time

Page 851: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

a==b#=>false

"%.6f"%a.to_f#=>"1195480202.282373"

"%.6f"%b.to_f#=>"1195480202.283415"

Time.new(2008,6,21,13,30,0,"+09:00")#=>2008-06-2113:30:00+0900

#AtripforRubyConf2007

t1=Time.new(2007,11,1,15,25,0,"+09:00")#JST(Narita)

t2=Time.new(2007,11,1,12,5,0,"-05:00")#CDT(Minneapolis)

t3=Time.new(2007,11,1,13,25,0,"-05:00")#CDT(Minneapolis)

t4=Time.new(2007,11,1,16,53,0,"-04:00")#EDT(Charlotte)

t5=Time.new(2007,11,5,9,24,0,"-05:00")#EST(Charlotte)

t6=Time.new(2007,11,5,11,21,0,"-05:00")#EST(Detroit)

t7=Time.new(2007,11,5,13,45,0,"-05:00")#EST(Detroit)

t8=Time.new(2007,11,6,17,10,0,"+09:00")#JST(Narita)

p((t2-t1)/3600.0)#=>10.666666666666666

p((t4-t3)/3600.0)#=>2.466666666666667

p((t6-t5)/3600.0)#=>1.95

p((t8-t7)/3600.0)#=>13.416666666666666

CreatesanewTimeobjectforthecurrenttime.Thisissameas::newwithoutarguments.

Time.now#=>2009-06-2412:39:54+0900

now→time

utc(year)→timeutc(year,month)→timeutc(year,month,day)→timeutc(year,month,day,hour)→timeutc(year,month,day,hour,min)→timeutc(year,month,day,hour,min,sec_with_frac)→timeutc(year,month,day,hour,min,sec,usec_with_frac)→timeutc(sec,min,hour,day,month,year,dummy,

Page 852: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

CreatesaTimeobjectbasedongivenvalues,interpretedasUTC(GMT).Theyearmustbespecified.Othervaluesdefaulttotheminimumvalueforthatfield(andmaybeniloromitted).Monthsmaybespecifiedbynumbersfrom1to12,orbythethree-letterEnglishmonthnames.Hoursarespecifiedona24-hourclock(0..23).RaisesanArgumentErrorifanyvaluesareoutofrange.Willalsoaccepttenargumentsintheorderoutputby#to_a.

sec_with_fracandusec_with_fraccanhaveafractionalpart.

Time.utc(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01UTC

Time.gm(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01UTC

PublicInstanceMethods

Addition—Addssomenumberofseconds(possibly

dummy,dummy,dummy)→timegm(year)→timegm(year,month)→timegm(year,month,day)→timegm(year,month,day,hour)→timegm(year,month,day,hour,min)→timegm(year,month,day,hour,min,sec_with_frac)→timegm(year,month,day,hour,min,sec,usec_with_frac)→timegm(sec,min,hour,day,month,year,dummy,dummy,dummy,dummy)→time

time+numeric→time

Page 853: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

fractional)totimeandreturnsthatvalueasanewTimeobject.

t=Time.now#=>2007-11-1908:22:21-0600

t+(60*60*24)#=>2007-11-2008:22:21-0600

Difference—ReturnsanewTimeobjectthatrepresentsthedifferencebetweentimeandother_time,orsubtractsthegivennumberofsecondsinnumericfromtime.

t=Time.now#=>2007-11-1908:23:10-0600

t2=t+2592000#=>2007-12-1908:23:10-0600

t2-t#=>2592000.0

t2-2592000#=>2007-11-1908:23:10-0600

Comparison—Comparestimewithother_time.

-1,0,+1ornildependingonwhethertimeislessthan,equalto,orgreaterthanother_time.

nilisreturnedifthetwovaluesareincomparable.

t=Time.now#=>2007-11-1908:12:12-0600

t2=t+2592000#=>2007-12-1908:12:12-0600

t<=>t2#=>-1

t2<=>t#=>1

t=Time.now#=>2007-11-1908:13:38-0600

t2=t+0.1#=>2007-11-1908:13:38-0600

t.nsec#=>98222999

t2.nsec#=>198222999

t<=>t2#=>-1

t2<=>t#=>1

t<=>t#=>0

time-other_time→floattime-numeric→time

time<=>other_time→-1,0,+1ornil

Page 854: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Returnsacanonicalstringrepresentationoftime.

Time.now.asctime#=>"WedApr908:56:032003"

Returnsacanonicalstringrepresentationoftime.

Time.now.asctime#=>"WedApr908:56:032003"

Returnsthedayofthemonth(1..n)fortime.

t=Time.now#=>2007-11-1908:27:03-0600

t.day#=>19

t.mday#=>19

ReturnstrueiftimeoccursduringDaylightSavingTimeinitstimezone.

#CST6CDT:

Time.local(2000,1,1).zone#=>"CST"

Time.local(2000,1,1).isdst#=>false

Time.local(2000,1,1).dst?#=>false

Time.local(2000,7,1).zone#=>"CDT"

Time.local(2000,7,1).isdst#=>true

Time.local(2000,7,1).dst?#=>true

asctime→stringctime→string

asctime→stringctime→string

day→fixnummday→fixnum

isdst→trueorfalsedst?→trueorfalse

Page 855: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

#Asia/Tokyo:

Time.local(2000,1,1).zone#=>"JST"

Time.local(2000,1,1).isdst#=>false

Time.local(2000,1,1).dst?#=>false

Time.local(2000,7,1).zone#=>"JST"

Time.local(2000,7,1).isdst#=>false

Time.local(2000,7,1).dst?#=>false

Returnstrueiftimeandother_timearebothTimeobjectswiththesamesecondsandfractionalseconds.

ReturnstrueiftimerepresentsFriday.

t=Time.local(1987,12,18)#=>1987-12-1800:00:00-0600

t.friday?#=>true

ReturnsanewTimeobjectrepresentingtimeinUTC.

t=Time.local(2000,1,1,20,15,1)#=>2000-01-0120:15:01-0600

t.gmt?#=>false

y=t.getgm#=>2000-01-0202:15:01UTC

y.gmt?#=>true

t==y#=>true

ReturnsanewTimeobjectrepresentingtimeinlocaltime(usingthelocaltimezoneineffectforthis

eql?(other_time)

friday?→trueorfalse

getgm→new_timegetutc→new_time

getlocal→new_timegetlocal(utc_offset)→new_time

Page 856: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

process).

Ifutc_offsetisgiven,itisusedinsteadofthelocaltime.

t=Time.utc(2000,1,1,20,15,1)#=>2000-01-0120:15:01UTC

t.utc?#=>true

l=t.getlocal#=>2000-01-0114:15:01-0600

l.utc?#=>false

t==l#=>true

j=t.getlocal("+09:00")#=>2000-01-0205:15:01+0900

j.utc?#=>false

t==j#=>true

ReturnsanewTimeobjectrepresentingtimeinUTC.

t=Time.local(2000,1,1,20,15,1)#=>2000-01-0120:15:01-0600

t.gmt?#=>false

y=t.getgm#=>2000-01-0202:15:01UTC

y.gmt?#=>true

t==y#=>true

ReturnstrueiftimerepresentsatimeinUTC(GMT).

t=Time.now#=>2007-11-1908:15:23-0600

t.utc?#=>false

t=Time.gm(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01UTC

t.utc?#=>true

t=Time.now#=>2007-11-1908:16:03-0600

t.gmt?#=>false

t=Time.gm(2000,1,1,20,15,1)#=>2000-01-0120:15:01UTC

t.gmt?#=>true

getgm→new_timegetutc→new_time

utc?→trueorfalsegmt?→trueorfalse

Page 857: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstheoffsetinsecondsbetweenthetimezoneoftimeandUTC.

t=Time.gm(2000,1,1,20,15,1)#=>2000-01-0120:15:01UTC

t.gmt_offset#=>0

l=t.getlocal#=>2000-01-0114:15:01-0600

l.gmt_offset#=>-21600

ConvertstimetoUTC(GMT),modifyingthereceiver.

t=Time.now#=>2007-11-1908:18:31-0600

t.gmt?#=>false

t.gmtime#=>2007-11-1914:18:31UTC

t.gmt?#=>true

t=Time.now#=>2007-11-1908:18:51-0600

t.utc?#=>false

t.utc#=>2007-11-1914:18:51UTC

t.utc?#=>true

ReturnstheoffsetinsecondsbetweenthetimezoneoftimeandUTC.

t=Time.gm(2000,1,1,20,15,1)#=>2000-01-0120:15:01UTC

t.gmt_offset#=>0

l=t.getlocal#=>2000-01-0114:15:01-0600

l.gmt_offset#=>-21600

gmt_offset→fixnumgmtoff→fixnumutc_offset→fixnum

gmtime→timeutc→time

gmt_offset→fixnumgmtoff→fixnumutc_offset→fixnum

Page 858: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsahashcodeforthisTimeobject.

SeealsoObject#hash.

Returnsthehouroftheday(0..23)fortime.

t=Time.now#=>2007-11-1908:26:20-0600

t.hour#=>8

Returnsastringrepresentingtime.Equivalenttocallingstrftimewiththeappropriateformatstring.

t=Time.now

t.to_s=>"2012-11-1018:16:12+0100"

t.strftime"%Y-%m-%d%H:%M:%S%z"=>"2012-11-1018:16:12+0100"

t.utc.to_s=>"2012-11-1017:16:12UTC"

t.strftime"%Y-%m-%d%H:%M:%SUTC"=>"2012-11-1017:16:12UTC"

ReturnstrueiftimeoccursduringDaylightSavingTimeinitstimezone.

#CST6CDT:

Time.local(2000,1,1).zone#=>"CST"

Time.local(2000,1,1).isdst#=>false

Time.local(2000,1,1).dst?#=>false

Time.local(2000,7,1).zone#=>"CDT"

Time.local(2000,7,1).isdst#=>true

hash→fixnum

hour→fixnum

inspect→stringto_s→string

isdst→trueorfalsedst?→trueorfalse

Page 859: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Time.local(2000,7,1).dst?#=>true

#Asia/Tokyo:

Time.local(2000,1,1).zone#=>"JST"

Time.local(2000,1,1).isdst#=>false

Time.local(2000,1,1).dst?#=>false

Time.local(2000,7,1).zone#=>"JST"

Time.local(2000,7,1).isdst#=>false

Time.local(2000,7,1).dst?#=>false

Convertstimetolocaltime(usingthelocaltimezoneineffectforthisprocess)modifyingthereceiver.

Ifutc_offsetisgiven,itisusedinsteadofthelocaltime.

t=Time.utc(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01UTC

t.utc?#=>true

t.localtime#=>2000-01-0114:15:01-0600

t.utc?#=>false

t.localtime("+09:00")#=>2000-01-0205:15:01+0900

t.utc?#=>false

Returnsthedayofthemonth(1..n)fortime.

t=Time.now#=>2007-11-1908:27:03-0600

t.day#=>19

t.mday#=>19

Returnstheminuteofthehour(0..59)fortime.

localtime→timelocaltime(utc_offset)→time

day→fixnummday→fixnum

min→fixnum

Page 860: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

t=Time.now#=>2007-11-1908:25:51-0600

t.min#=>25

Returnsthemonthoftheyear(1..12)fortime.

t=Time.now#=>2007-11-1908:27:30-0600

t.mon#=>11

t.month#=>11

ReturnstrueiftimerepresentsMonday.

t=Time.local(2003,8,4)#=>2003-08-0400:00:00-0500

pt.monday?#=>true

Returnsthemonthoftheyear(1..12)fortime.

t=Time.now#=>2007-11-1908:27:30-0600

t.mon#=>11

t.month#=>11

Returnsthenumberofnanosecondsfortime.

t=Time.now#=>2007-11-1715:18:03+0900

"%10.9f"%t.to_f#=>"1195280283.536151409"

t.nsec#=>536151406

Thelowestdigitsofto_fandnsecaredifferent

mon→fixnummonth→fixnum

monday?→trueorfalse

mon→fixnummonth→fixnum

nsec→inttv_nsec→int

Page 861: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

becauseIEEE754doubleisnotaccurateenoughtorepresenttheexactnumberofnanosecondssincetheEpoch.

Themoreaccuratevalueisreturnedbynsec.

Roundssubsecondstoagivenprecisionindecimaldigits(0digitsbydefault).ItreturnsanewTimeobject.ndigitsshouldbezeroorpositiveinteger.

require'time'

t=Time.utc(2010,3,30,5,43,"25.123456789".to_r)

pt.iso8601(10)#=>"2010-03-30T05:43:25.1234567890Z"

pt.round.iso8601(10)#=>"2010-03-30T05:43:25.0000000000Z"

pt.round(0).iso8601(10)#=>"2010-03-30T05:43:25.0000000000Z"

pt.round(1).iso8601(10)#=>"2010-03-30T05:43:25.1000000000Z"

pt.round(2).iso8601(10)#=>"2010-03-30T05:43:25.1200000000Z"

pt.round(3).iso8601(10)#=>"2010-03-30T05:43:25.1230000000Z"

pt.round(4).iso8601(10)#=>"2010-03-30T05:43:25.1235000000Z"

pt.round(5).iso8601(10)#=>"2010-03-30T05:43:25.1234600000Z"

pt.round(6).iso8601(10)#=>"2010-03-30T05:43:25.1234570000Z"

pt.round(7).iso8601(10)#=>"2010-03-30T05:43:25.1234568000Z"

pt.round(8).iso8601(10)#=>"2010-03-30T05:43:25.1234567900Z"

pt.round(9).iso8601(10)#=>"2010-03-30T05:43:25.1234567890Z"

pt.round(10).iso8601(10)#=>"2010-03-30T05:43:25.1234567890Z"

t=Time.utc(1999,12,31,23,59,59)

p((t+0.4).round.iso8601(3))#=>"1999-12-31T23:59:59.000Z"

p((t+0.49).round.iso8601(3))#=>"1999-12-31T23:59:59.000Z"

p((t+0.5).round.iso8601(3))#=>"2000-01-01T00:00:00.000Z"

p((t+1.4).round.iso8601(3))#=>"2000-01-01T00:00:00.000Z"

p((t+1.49).round.iso8601(3))#=>"2000-01-01T00:00:00.000Z"

p((t+1.5).round.iso8601(3))#=>"2000-01-01T00:00:01.000Z"

t=Time.utc(1999,12,31,23,59,59)

p(t+0.123456789).round(4).iso8601(6)#=>"1999-12-31T23:59:59.123500Z"

round([ndigits])→new_time

saturday?→trueorfalse

Page 862: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnstrueiftimerepresentsSaturday.

t=Time.local(2006,6,10)#=>2006-06-1000:00:00-0500

t.saturday?#=>true

Returnsthesecondoftheminute(0..60)fortime.

Note:Secondsrangefromzeroto60toallowthesystemtoinjectleapseconds.Seeen.wikipedia.org/wiki/Leap_secondforfurtherdetails.

t=Time.now#=>2007-11-1908:25:02-0600

t.sec#=>2

Formatstimeaccordingtothedirectivesinthegivenformatstring.

Thedirectivesbeginwithapercent(%)character.Anytextnotlistedasadirectivewillbepassedthroughtotheoutputstring.

Thedirectiveconsistsofapercent(%)character,zeroormoreflags,optionalminimumfieldwidth,optionalmodifierandaconversionspecifierasfollows:

%<flags><width><modifier><conversion>

Flags:

-don'tpadanumericaloutput

_usespacesforpadding

0usezerosforpadding

^upcasetheresultstring

#changecase

:usecolonsfor%z

sec→fixnum

strftime(string)→string

Page 863: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Theminimumfieldwidthspecifiestheminimumwidth.

Themodifiersare“E”and“O”.Theyareignored.

Formatdirectives:

Date(Year,Month,Day):

%Y-Yearwithcenturyifprovided,willpadresultatleast4digits.

-0001,0000,1995,2009,14292,etc.

%C-year/100(roundeddownsuchas20in2009)

%y-year%100(00..99)

%m-Monthoftheyear,zero-padded(01..12)

%_mblank-padded(1..12)

%-mno-padded(1..12)

%B-Thefullmonthname(``January'')

%^Buppercased(``JANUARY'')

%b-Theabbreviatedmonthname(``Jan'')

%^buppercased(``JAN'')

%h-Equivalentto%b

%d-Dayofthemonth,zero-padded(01..31)

%-dno-padded(1..31)

%e-Dayofthemonth,blank-padded(1..31)

%j-Dayoftheyear(001..366)

Time(Hour,Minute,Second,Subsecond):

%H-Houroftheday,24-hourclock,zero-padded(00..23)

%k-Houroftheday,24-hourclock,blank-padded(0..23)

%I-Houroftheday,12-hourclock,zero-padded(01..12)

%l-Houroftheday,12-hourclock,blank-padded(1..12)

%P-Meridianindicator,lowercase(``am''or``pm'')

%p-Meridianindicator,uppercase(``AM''or``PM'')

%M-Minuteofthehour(00..59)

%S-Secondoftheminute(00..60)

%L-Millisecondofthesecond(000..999)

Thedigitsundermillisecondaretruncatedtonotproduce1000.

%N-Fractionalsecondsdigits,defaultis9digits(nanosecond)

%3Nmillisecond(3digits)

%6Nmicrosecond(6digits)

%9Nnanosecond(9digits)

%12Npicosecond(12digits)

Page 864: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

%15Nfemtosecond(15digits)

%18Nattosecond(18digits)

%21Nzeptosecond(21digits)

%24Nyoctosecond(24digits)

Thedigitsunderthespecifiedlengtharetruncatedtoavoid

carryup.

Timezone:

%z-TimezoneashourandminuteoffsetfromUTC(e.g.+0900)

%:z-hourandminuteoffsetfromUTCwithacolon(e.g.+09:00)

%::z-hour,minuteandsecondoffsetfromUTC(e.g.+09:00:00)

%Z-Abbreviatedtimezonenameorsimilarinformation.(OSdependent)

Weekday:

%A-Thefullweekdayname(``Sunday'')

%^Auppercased(``SUNDAY'')

%a-Theabbreviatedname(``Sun'')

%^auppercased(``SUN'')

%u-Dayoftheweek(Mondayis1,1..7)

%w-Dayoftheweek(Sundayis0,0..6)

ISO8601week-basedyearandweeknumber:

ThefirstweekofYYYYstartswithaMondayandincludesYYYY-01-04.

Thedaysintheyearbeforethefirstweekareinthelastweekof

thepreviousyear.

%G-Theweek-basedyear

%g-Thelast2digitsoftheweek-basedyear(00..99)

%V-Weeknumberoftheweek-basedyear(01..53)

Weeknumber:

ThefirstweekofYYYYthatstartswithaSundayorMonday(accordingto%U

or%W).Thedaysintheyearbeforethefirstweekareinweek0.

%U-Weeknumberoftheyear.TheweekstartswithSunday.(00..53)

%W-Weeknumberoftheyear.TheweekstartswithMonday.(00..53)

SecondssincetheEpoch:

%s-Numberofsecondssince1970-01-0100:00:00UTC.

Literalstring:

%n-Newlinecharacter(\n)

%t-Tabcharacter(\t)

%%-Literal``%''character

Combination:

%c-dateandtime(%a%b%e%T%Y)

%D-Date(%m/%d/%y)

%F-TheISO8601dateformat(%Y-%m-%d)

Page 865: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

%v-VMSdate(%e-%^b-%4Y)

%x-Sameas%D

%X-Sameas%T

%r-12-hourtime(%I:%M:%S%p)

%R-24-hourtime(%H:%M)

%T-24-hourtime(%H:%M:%S)

Thismethodissimilartostrftime()functiondefinedinISOCandPOSIX.

WhilealldirectivesarelocaleindependentsinceRuby1.9,%Zisplatformdependent.So,theresultmaydifferevenifthesameformatstringisusedinothersystemssuchasC.

%zisrecommendedover%Z.%Zdoesn'tidentifythetimezone.Forexample,“CST”isusedatAmerica/Chicago(-06:00),America/Havana(-05:00),Asia/Harbin(+08:00),Australia/Darwin(+09:30)andAustralia/Adelaide(+10:30).Also,%Zishighlydependentontheoperatingsystem.Forexample,itmaygenerateanonASCIIstringonJapaneseWindows.i.e.theresultcanbedifferentto“JST”.Sothenumerictimezoneoffset,%z,isrecommended.

Examples:

t=Time.new(2007,11,19,8,37,48,"-06:00")#=>2007-11-1908:37:48-0600

t.strftime("Printedon%m/%d/%Y")#=>"Printedon11/19/2007"

t.strftime("at%I:%M%p")#=>"at08:37AM"

VariousISO8601formats:

%Y%m%d=>20071119Calendardate(basic)

%F=>2007-11-19Calendardate(extended)

%Y-%m=>2007-11Calendardate,reducedaccuracy,specificmonth

%Y=>2007Calendardate,reducedaccuracy,specificyear

%C=>20Calendardate,reducedaccuracy,specificcentury

%Y%j=>2007323Ordinaldate(basic)

%Y-%j=>2007-323Ordinaldate(extended)

%GW%V%u=>2007W471Weekdate(basic)

%G-W%V-%u=>2007-W47-1Weekdate(extended)

Page 866: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

%GW%V=>2007W47Weekdate,reducedaccuracy,specificweek(basic)

%G-W%V=>2007-W47Weekdate,reducedaccuracy,specificweek(extended)

%H%M%S=>083748Localtime(basic)

%T=>08:37:48Localtime(extended)

%H%M=>0837Localtime,reducedaccuracy,specificminute(basic)

%H:%M=>08:37Localtime,reducedaccuracy,specificminute(extended)

%H=>08Localtime,reducedaccuracy,specifichour

%H%M%S,%L=>083748,000Localtimewithdecimalfraction,commaasdecimalsign(basic)

%T,%L=>08:37:48,000Localtimewithdecimalfraction,commaasdecimalsign(extended)

%H%M%S.%L=>083748.000Localtimewithdecimalfraction,fullstopasdecimalsign(basic)

%T.%L=>08:37:48.000Localtimewithdecimalfraction,fullstopasdecimalsign(extended)

%H%M%S%z=>083748-0600LocaltimeandthedifferencefromUTC(basic)

%T%:z=>08:37:48-06:00LocaltimeandthedifferencefromUTC(extended)

%Y%m%dT%H%M%S%z=>20071119T083748-0600Dateandtimeofdayforcalendardate(basic)

%FT%T%:z=>2007-11-19T08:37:48-06:00Dateandtimeofdayforcalendardate(extended)

%Y%jT%H%M%S%z=>2007323T083748-0600Dateandtimeofdayforordinaldate(basic)

%Y-%jT%T%:z=>2007-323T08:37:48-06:00Dateandtimeofdayforordinaldate(extended)

%GW%V%uT%H%M%S%z=>2007W471T083748-0600Dateandtimeofdayforweekdate(basic)

%G-W%V-%uT%T%:z=>2007-W47-1T08:37:48-06:00Dateandtimeofdayforweekdate(extended)

%Y%m%dT%H%M=>20071119T0837Calendardateandlocaltime(basic)

%FT%R=>2007-11-19T08:37Calendardateandlocaltime(extended)

%Y%jT%H%MZ=>2007323T0837ZOrdinaldateandUTCofday(basic)

%Y-%jT%RZ=>2007-323T08:37ZOrdinaldateandUTCofday(extended)

%GW%V%uT%H%M%z=>2007W471T0837-0600WeekdateandlocaltimeanddifferencefromUTC(basic)

%G-W%V-%uT%R%:z=>2007-W47-1T08:37-06:00WeekdateandlocaltimeanddifferencefromUTC(extended)

Returnsthefractionfortime.

Thereturnvaluecanbearationalnumber.

t=Time.now#=>2009-03-2622:33:12+0900

"%10.9f"%t.to_f#=>"1238074392.940563917"

t.subsec#=>(94056401/100000000)

Thelowestdigitsofto_fandsubsecaredifferentbecauseIEEE754doubleisnotaccurateenoughtorepresenttherationalnumber.

Themoreaccuratevalueisreturnedbysubsec.

subsec→number

Page 867: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsanewTimeobject,onesecondlaterthantime.#succisobsoletesince1.9.2fortimeisnotadiscretevalue.

t=Time.now#=>2007-11-1908:23:57-0600

t.succ#=>2007-11-1908:23:58-0600

Useinsteadtime+1

t+1#=>2007-11-1908:23:58-0600

ReturnstrueiftimerepresentsSunday.

t=Time.local(1990,4,1)#=>1990-04-0100:00:00-0600

t.sunday?#=>true

ReturnstrueiftimerepresentsThursday.

t=Time.local(1995,12,21)#=>1995-12-2100:00:00-0600

pt.thursday?#=>true

Returnsaten-elementarrayofvaluesfortime:

[sec,min,hour,day,month,year,wday,yday,isdst,zone]

Seetheindividualmethodsforanexplanationofthevalidrangesofeachvalue.Thetenelementscanbepasseddirectlyto::utcor::localtocreateanewTime

succ→new_time

sunday?→trueorfalse

thursday?→trueorfalse

to_a→array

Page 868: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

object.

t=Time.now#=>2007-11-1908:36:01-0600

now=t.to_a#=>[1,36,8,19,11,2007,1,323,false,"CST"]

ReturnsthevalueoftimeasafloatingpointnumberofsecondssincetheEpoch.

t=Time.now

"%10.5f"%t.to_f#=>"1270968744.77658"

t.to_i#=>1270968744

NotethatIEEE754doubleisnotaccurateenoughtorepresentthenumberofnanosecondssincetheEpoch.

ReturnsthevalueoftimeasanintegernumberofsecondssincetheEpoch.

t=Time.now

"%10.5f"%t.to_f#=>"1270968656.89607"

t.to_i#=>1270968656

ReturnsthevalueoftimeasarationalnumberofsecondssincetheEpoch.

t=Time.now

pt.to_r#=>(1270968792716287611/1000000000)

ThismethodsisintendedtobeusedtogetanaccuratevaluerepresentingthenanosecondssincetheEpoch.Youcanusethismethodtoconverttime

to_f→float

to_i→inttv_sec→int

to_r→a_rational

Page 869: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

toanotherEpoch.

Returnsastringrepresentingtime.Equivalenttocallingstrftimewiththeappropriateformatstring.

t=Time.now

t.to_s=>"2012-11-1018:16:12+0100"

t.strftime"%Y-%m-%d%H:%M:%S%z"=>"2012-11-1018:16:12+0100"

t.utc.to_s=>"2012-11-1017:16:12UTC"

t.strftime"%Y-%m-%d%H:%M:%SUTC"=>"2012-11-1017:16:12UTC"

ReturnstrueiftimerepresentsTuesday.

t=Time.local(1991,2,19)#=>1991-02-1900:00:00-0600

pt.tuesday?#=>true

Returnsthenumberofnanosecondsfortime.

t=Time.now#=>2007-11-1715:18:03+0900

"%10.9f"%t.to_f#=>"1195280283.536151409"

t.nsec#=>536151406

Thelowestdigitsofto_fandnsecaredifferentbecauseIEEE754doubleisnotaccurateenoughtorepresenttheexactnumberofnanosecondssincetheEpoch.

Themoreaccuratevalueisreturnedbynsec.

inspect→stringto_s→string

tuesday?→trueorfalse

nsec→inttv_nsec→int

Page 870: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsthevalueoftimeasanintegernumberofsecondssincetheEpoch.

t=Time.now

"%10.5f"%t.to_f#=>"1270968656.89607"

t.to_i#=>1270968656

Returnsthenumberofmicrosecondsfortime.

t=Time.now#=>2007-11-1908:03:26-0600

"%10.6f"%t.to_f#=>"1195481006.775195"

t.usec#=>775195

Returnsthenumberofmicrosecondsfortime.

t=Time.now#=>2007-11-1908:03:26-0600

"%10.6f"%t.to_f#=>"1195481006.775195"

t.usec#=>775195

ConvertstimetoUTC(GMT),modifyingthereceiver.

t=Time.now#=>2007-11-1908:18:31-0600

t.gmt?#=>false

t.gmtime#=>2007-11-1914:18:31UTC

t.gmt?#=>true

t=Time.now#=>2007-11-1908:18:51-0600

to_i→inttv_sec→int

usec→inttv_usec→int

usec→inttv_usec→int

gmtime→timeutc→time

Page 871: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

t.utc?#=>false

t.utc#=>2007-11-1914:18:51UTC

t.utc?#=>true

ReturnstrueiftimerepresentsatimeinUTC(GMT).

t=Time.now#=>2007-11-1908:15:23-0600

t.utc?#=>false

t=Time.gm(2000,"jan",1,20,15,1)#=>2000-01-0120:15:01UTC

t.utc?#=>true

t=Time.now#=>2007-11-1908:16:03-0600

t.gmt?#=>false

t=Time.gm(2000,1,1,20,15,1)#=>2000-01-0120:15:01UTC

t.gmt?#=>true

ReturnstheoffsetinsecondsbetweenthetimezoneoftimeandUTC.

t=Time.gm(2000,1,1,20,15,1)#=>2000-01-0120:15:01UTC

t.gmt_offset#=>0

l=t.getlocal#=>2000-01-0114:15:01-0600

l.gmt_offset#=>-21600

Returnsanintegerrepresentingthedayoftheweek,0..6,withSunday==0.

t=Time.now#=>2007-11-2002:35:35-0600

t.wday#=>2

t.sunday?#=>false

utc?→trueorfalsegmt?→trueorfalse

gmt_offset→fixnumgmtoff→fixnumutc_offset→fixnum

wday→fixnum

Page 872: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

t.monday?#=>false

t.tuesday?#=>true

t.wednesday?#=>false

t.thursday?#=>false

t.friday?#=>false

t.saturday?#=>false

ReturnstrueiftimerepresentsWednesday.

t=Time.local(1993,2,24)#=>1993-02-2400:00:00-0600

pt.wednesday?#=>true

Returnsanintegerrepresentingthedayoftheyear,1..366.

t=Time.now#=>2007-11-1908:32:31-0600

t.yday#=>323

Returnstheyearfortime(includingthecentury).

t=Time.now#=>2007-11-1908:27:51-0600

t.year#=>2007

Returnsthenameofthetimezoneusedfortime.AsofRuby1.8,returns“UTC''ratherthan“GMT''forUTCtimes.

t=Time.gm(2000,"jan",1,20,15,1)

t.zone#=>"UTC"

t=Time.local(2000,"jan",1,20,15,1)

t.zone#=>"CST"

wednesday?→trueorfalse

yday→fixnum

year→fixnum

zone→string

Page 873: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 874: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classTracePointAclassthatprovidesthefunctionalityofKernel#set_trace_funcinaniceObject-OrientedAPI.

Page 875: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Example

WecanuseTracePointtogatherinformationspecificallyforexceptions:

trace=TracePoint.new(:raise)do|tp|

p[tp.lineno,tp.event,tp.raised_exception]

end

#=>#<TracePoint:disabled>

trace.enable

#=>false

0/0

#=>[5,:raise,#<ZeroDivisionError:dividedby0>]

Page 876: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Events

Ifyoudon'tspecifythetypeofeventsyouwanttolistenfor,TracePointwillincludeallavailableevents.

Notedonotdependoncurrenteventset,asthislistissubjecttochange.Instead,itisrecommendedyouspecifythetypeofeventsyouwanttouse.

Tofilterwhatistraced,youcanpassanyofthefollowingasevents:

:line

executecodeonanewline

:class

startaclassormoduledefinition

:end

finishaclassormoduledefinition

:call

callaRubymethod

:return

returnfromaRubymethod

:c_call

Page 877: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

callaC-languageroutine

:c_return

returnfromaC-languageroutine

:raise

raiseanexception

:b_call

eventhookatblockentry

:b_return

eventhookatblockending

:thread_begin

eventhookatthreadbeginning

:thread_end

eventhookatthreadending

InFilesvm_trace.c

ParentObject

PublicClassMethods

Page 878: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

ReturnsanewTracePointobject,notenabledbydefault.

Next,inordertoactivatethetrace,youmustuse#enable

trace=TracePoint.new(:call)do|tp|

p[tp.lineno,tp.defined_class,tp.method_id,tp.event

end

#=>#<TracePoint:disabled>

trace.enable

#=>false

puts"Hello,TracePoint!"

#...

#[48,IRB::Notifier::AbstractNotifier,:printf,:call]

#...

Whenyouwanttodeactivatethetrace,youmustuse#disable

trace.disable

SeeEventsatTracePointforpossibleeventsandmoreinformation.

Ablockmustbegiven,otherwiseaThreadErrorisraised.

Ifthetracemethodisn'tincludedinthegiveneventsfilter,aRuntimeErrorisraised.

TracePoint.trace(:line)do|tp|

ptp.raised_exception

end

#=>RuntimeError:'raised_exception'notsupportedbythisevent

Ifthetracemethodiscalledoutsideblock,aRuntimeErrorisraised.

new(*events){|obj|block}→obj

Page 879: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

TracePoint.trace(:line)do|tp|

$tp=tp

end

$tp.line#=>accessfromoutside(RuntimeError)

Accessfromotherthreadsisalsoforbidden.

ReturnsinternalinformationofTracePoint.

Thecontentsofthereturnedvalueareimplementationspecific.Itmaybechangedinfuture.

ThismethodisonlyfordebuggingTracePointitself.

Aconveniencemethodfor::new,thatactivatesthetraceautomatically.

trace=TracePoint.trace(:call){|tp|[tp.lineno,tp.

#=>#<TracePoint:enabled>

trace.enabled?#=>true

PublicInstanceMethods

Returnthegeneratedbindingobjectfromevent

Returnclassormoduleofthemethodbeingcalled.

classC;deffoo;end;end

trace=TracePoint.new(:call)do|tp|

ptp.defined_class#=>C

stat→obj

trace(*events){|obj|block}→obj

binding()

defined_class()

Page 880: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end.enabledo

C.new.foo

end

Ifmethodisdefinedbyamodule,thenthatmoduleisreturned.

moduleM;deffoo;end;end

classC;includeM;end;

trace=TracePoint.new(:call)do|tp|

ptp.defined_class#=>M

end.enabledo

C.new.foo

end

Note:defined_classreturnssingletonclass.6thblockparameterofKernel#set_trace_funcpassesoriginalclassofattachedbysingletonclass.

ThisisadifferencebetweenKernel#set_trace_funcandTracePoint.

classC;defself.foo;end;end

trace=TracePoint.new(:call)do|tp|

ptp.defined_class#=>#<Class:C>

end.enabledo

C.foo

end

Deactivatesthetrace

Returntrueiftracewasenabled.Returnfalseiftracewasdisabled.

trace.enabled?#=>true

trace.disable#=>false(previousstatus)

trace.enabled?#=>false

trace.disable#=>false

disable→trueorfalsedisable{block}→obj

Page 881: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ifablockisgiven,thetracewillonlybedisablewithinthescopeoftheblock.

trace.enabled?

#=>true

trace.disabledo

trace.enabled?

#onlydisabledforthisblock

end

trace.enabled?

#=>true

Note:Youcannotaccesseventhookswithintheblock.

trace.disable{ptp.lineno}

#=>RuntimeError:accessfromoutside

Activatesthetrace

Returntrueiftracewasenabled.Returnfalseiftracewasdisabled.

trace.enabled?#=>false

trace.enable#=>false(previousstate)

#traceisenabled

trace.enabled?#=>true

trace.enable#=>true(previousstate)

#traceisstillenabled

Ifablockisgiven,thetracewillonlybeenabledwithinthescopeoftheblock.

trace.enabled?

#=>false

trace.enabledo

trace.enabled?

#onlyenabledforthisblock

enable→trueorfalseenable{block}→obj

Page 882: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

end

trace.enabled?

#=>false

Note:Youcannotaccesseventhookswithintheblock.

trace.enable{ptp.lineno}

#=>RuntimeError:accessfromoutside

Thecurrentstatusofthetrace

Typeofevent

SeeEventsatTracePointformoreinformation.

Returnastringcontainingahuman-readableTracePointstatus.

Linenumberoftheevent

Returnthenameofthemethodbeingcalled

Pathofthefilebeingrun

enabled?→trueorfalse

event()

inspect→string

lineno()

method_id()

path()

raised_exception()

Page 883: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Valuefromexceptionraisedonthe:raiseevent

Returnvaluefrom:return,c_return,andb_returnevent

Returnthetraceobjectduringevent

Sameas#binding:

trace.binding.eval('self')

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

return_value()

self()

Page 884: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classTrueClassTheglobalvaluetrueistheonlyinstanceofclassTrueClassandrepresentsalogicallytruevalueinbooleanexpressions.Theclassprovidesoperatorsallowingtruetobeusedinlogicalexpressions.

InFilesobject.c

ParentObject

PublicInstanceMethods

And—Returnsfalseifobjisnilorfalse,trueotherwise.

ExclusiveOr—Returnstrueifobjisnilorfalse,falseotherwise.

Aliasfor:to_s

true&obj→trueorfalse

true^obj→!obj

inspect()

Page 885: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Thestringrepresentationoftrueis“true”.

Alsoaliasedas:inspect

Or—Returnstrue.Asobjisanargumenttoamethodcall,itisalwaysevaluated;thereisnoshort-circuitevaluationinthiscase.

true|puts("or")

true||puts("logicalor")

produces:

or

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

to_s→"true"

true|obj→true

Page 886: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classTypeErrorRaisedwhenencounteringanobjectthatisnotoftheexpectedtype.

[1,2,3].first("two")

raisestheexception:

TypeError:noimplicitconversionofStringintoInteger

InFileserror.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 887: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classUnboundMethodRubysupportstwoformsofobjectifiedmethods.ClassMethodisusedtorepresentmethodsthatareassociatedwithaparticularobject:thesemethodobjectsareboundtothatobject.BoundmethodobjectsforanobjectcanbecreatedusingObject#method.

Rubyalsosupportsunboundmethods;methodsobjectsthatarenotassociatedwithaparticularobject.ThesecanbecreatedeitherbycallingModule#instance_methodorbycallingunbindonaboundmethodobject.TheresultofbothoftheseisanUnboundMethodobject.

Unboundmethodscanonlybecalledaftertheyareboundtoanobject.Thatobjectmustbebeakind_of?themethod'soriginalclass.

classSquare

defarea

@side*@side

end

definitialize(side)

@side=side

end

end

area_un=Square.instance_method(:area)

s=Square.new(12)

area=area_un.bind(s)

area.call#=>144

Page 888: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Unboundmethodsareareferencetothemethodatthetimeitwasobjectified:subsequentchangestotheunderlyingclasswillnotaffecttheunboundmethod.

classTest

deftest

:original

end

end

um=Test.instance_method(:test)

classTest

deftest

:modified

end

end

t=Test.new

t.test#=>:modified

um.bind(t).call#=>:original

InFilesproc.c

ParentObject

PublicInstanceMethods

Twomethodobjectsareequaliftheyareboundto

eql?(other_meth)→trueorfalsemeth==other_meth→trueorfalse

Page 889: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

thesameobjectandrefertothesamemethoddefinitionandtheirownersarethesameclassormodule.

Returnsanindicationofthenumberofargumentsacceptedbyamethod.Returnsanonnegativeintegerformethodsthattakeafixednumberofarguments.ForRubymethodsthattakeavariablenumberofarguments,returns-n-1,wherenisthenumberofrequiredarguments.FormethodswritteninC,returns-1ifthecalltakesavariablenumberofarguments.

classC

defone;end

deftwo(a);end

defthree(*a);end

deffour(a,b);end

deffive(a,b,*c);end

defsix(a,b,*c,&d);end

end

c=C.new

c.method(:one).arity#=>0

c.method(:two).arity#=>1

c.method(:three).arity#=>-1

c.method(:four).arity#=>2

c.method(:five).arity#=>-3

c.method(:six).arity#=>-3

"cat".method(:size).arity#=>0

"cat".method(:replace).arity#=>1

"cat".method(:squeeze).arity#=>-1

"cat".method(:count).arity#=>-1

Bindumethtoobj.IfKlasswastheclassfromwhichumethwasobtained,obj.kind_of?(Klass)mustbetrue.

arity→fixnum

bind(obj)→method

Page 890: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classA

deftest

puts"Intest,class=#{self.class}"

end

end

classB<A

end

classC<B

end

um=B.instance_method(:test)

bm=um.bind(C.new)

bm.call

bm=um.bind(B.new)

bm.call

bm=um.bind(A.new)

bm.call

produces:

Intest,class=C

Intest,class=B

prog.rb:16:in%xbind':bindargumentmustbeaninstanceofB(TypeError)

fromprog.rb:16

Returnsacloneofthismethod.

classA

deffoo

return"bar"

end

end

m=A.new.method(:foo)

m.call#=>"bar"

n=m.clone.call#=>"bar"

Twomethodobjectsareequaliftheyareboundto

clone→new_method

eql?(other_meth)→trueorfalsemeth==other_meth→trueorfalse

Page 891: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

thesameobjectandrefertothesamemethoddefinitionandtheirownersarethesameclassormodule.

Returnsahashvaluecorrespondingtothemethodobject.

SeealsoObject#hash.

Returnsthenameoftheunderlyingmethod.

"cat".method(:count).inspect#=>"#<Method:String#count>"

Returnsthenameofthemethod.

Returnstheoriginalnameofthemethod.

Returnstheclassormodulethatdefinesthemethod.

Returnstheparameterinformationofthismethod.

ReturnstheRubysourcefilenameandlinenumbercontainingthismethodornilifthismethodwasnot

hash→integer

to_s→stringinspect→string

name→symbol

original_name→symbol

owner→class_or_module

parameters→array

source_location→[String,Fixnum]

Page 892: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

definedinRuby(i.e.native)

ReturnsaMethodofsuperclass,whichwouldbecalledwhensuperisused.

Returnsthenameoftheunderlyingmethod.

"cat".method(:count).inspect#=>"#<Method:String#count>"

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

super_method()

to_s→stringinspect→string

Page 893: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classUncaughtThrowErrorRaisedwhenthrowiscalledwithatagwhichdoesnothavecorrespondingcatchblock.

throw"foo","bar"

raisestheexception:

UncaughtThrowError:uncaughtthrow"foo"

InFilesvm_eval.c

ParentArgError

PublicClassMethods

Document-class:UncaughtThrowError

Raisedwhenthrowiscalledwithatagwhichdoesnothavecorrespondingcatchblock.

throw"foo","bar"

raisestheexception:

new(*args)

Page 894: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

UncaughtThrowError:uncaughtthrow"foo"

PublicInstanceMethods

Returnthetagobjectwhichwascalledfor.

Returnsformattedmessagewiththeinspectedtag.

Returnthereturnvaluewhichwascalledfor.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

tag→obj

to_s→string

value→obj

Page 895: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classZeroDivisionErrorRaisedwhenattemptingtodivideanintegerby0.

42/0

#=>ZeroDivisionError:dividedby0

Notethatonlydivisionbyanexact0willraisetheexception:

42/0.0#=>Float::INFINITY

42/-0.0#=>-Float::INFINITY

0/0.0#=>NaN

InFilesnumeric.c

ParentStandardError

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 896: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

classfatalfatalisanExceptionthatisraisedwhenrubyhasencounteredafatalerrorandmustexit.Youarenotabletorescuefatal.

InFileserror.c

ParentException

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.

Page 897: Ruby 2.2.4 Core API Reference API ReferenceRuby 2.2.4 Core API Reference API Reference This is the API documentation for 'Ruby 2.2.4 Core API Reference API Reference

Ruby2.2.4CoreAPIReferenceAPIReferenceThisistheAPIdocumentationfor'Ruby2.2.4CoreAPIReferenceAPIReference'.

GeneratedbyRDoc3.12.2.GeneratedwiththeDarkfishRdocGenerator3.