# def
define a method; body runs on call, returns the last expression
def greet; "hi"; end; greet # => "hi"
rubylang v0.1.3 · Ruby on fusevm · lex/parse → AST → bytecode → Cranelift JIT · MIT · in active development
Every reserved keyword and builtin method the current rubylang build recognizes, grouped by keyword set then class and module. This page is generated from the language-server corpus (src/lsp.rs) by the gen-docs binary, so it stays in sync with what the runtime and editor tooling actually know about. Keywords mirror lexer.rs; each method row mirrors a real dispatch arm in src/builtins.rs.
defdefine a method; body runs on call, returns the last expression
def greet; "hi"; end; greet # => "hi"
endclose a def/class/module/do/if/case/begin block
class A; end # 'end' closes the class body
classopen or reopen a class; `class A < B` sets the superclass
class B < Object; end; B.superclass # => Object
moduleopen or reopen a module (namespace / mixin)
module M; end; M.class # => Module
selfthe current receiver object
class A; def me; self; end; end; A.new.me.class # => A
supercall the same method in the superclass (bare = pass same args)
class B<A; def f; super+1; end; end # calls A#f
ifconditional; also the `expr if cond` statement modifier
x = 5 if true; x # => 5
elsifadditional condition branch inside an if
if false then 1 elsif true then 2 end # => 2
elsefallback branch of an if/unless/case/begin
if false then 1 else 2 end # => 2
unlessnegated conditional; also the `expr unless cond` modifier
"y" unless false # => "y"
casemulti-way branch matched by `when` via `===`
case 2; when 2 then "b"; end # => "b"
whena case branch; matches its value against the subject with `===`
case 2; when 1..3 then "in"; end # => "in"
whileloop while the condition is truthy; also a statement modifier
i=0; i+=1 while i<3; i # => 3
untilloop until the condition is truthy; also a statement modifier
i=0; i+=1 until i>=3; i # => 3
foriterate `for x in enumerable` without a new scope
for x in [1,2,3]; print x; end # prints 123
inthe `for x in …` separator and case/in pattern-match clause
case [1,2]; in [a,b]; a+b; end # => 3
doopen a block (`each do |x| … end`) or a while/for body
[1,2].each do |n| print n end # prints 12
thenoptional separator after an if/when condition
if true then 1 else 2 end # => 1
yieldinvoke the block passed to the current method
def f; yield 5; end; f { |x| p x } # prints 5
returnreturn a value from the current method (nil if omitted)
def f; return 9; end; f # => 9
breakexit the nearest loop/block, optionally with a value
[1,2,3].each { |n| break n if n==2 } # => 2
nextskip to the next loop/block iteration, optionally with a value
[1,2,3].map { |n| next 0 if n==2; n } # => [1, 0, 3]
retryre-run the begin body from a rescue clause
a=0; begin; a+=1; raise if a<2; rescue; retry if a<2; end; a # => 2
beginopen an exception-handling block (rescue/ensure/else)
begin; raise "e"; rescue => e; e.message; end # => "e"
rescuehandle a raised exception; also the `expr rescue fallback` modifier
1/0 rescue "safe" # => "safe"
ensureblock that always runs whether or not an exception was raised
begin; 1; ensure; p "always"; end # prints always
andlow-precedence logical AND (short-circuits)
(true and false) # => false
orlow-precedence logical OR (short-circuits)
(nil or 2) # => 2
notlow-precedence logical negation
(not true) # => false
nilthe sole NilClass instance; the only falsey object besides false
nil.nil? # => true
truethe sole TrueClass instance
(true && 1) # => 1
falsethe sole FalseClass instance (falsey)
(false || 1) # => 1
aliasgive a method a second name: `alias new old`
class A; def old; 1; end; alias new old; end; A.new.new # => 1
defined?describe the expression's kind ("method"/"expression"/…) or nil
defined?(String) # => "constant"
putsprint each arg (arrays recursed) each on its own line
puts "hi" # => nil (prints hi)
printprint args joined by $, terminated by $\ (both nil default)
print "hi" # => nil (prints hi)
pprint inspect of each arg; return arg/array/nil
p 42 # => 42 (also prints 42)
ppalias of p (no pretty-printing)
pp [1,2] # => [1, 2] (also prints it)
requireno-op: always returns true (no file loaded)
require "json" # => true (nothing loaded)
require_relativeno-op: always returns true (no file loaded)
require_relative "x" # => true (no-op)
loadno-op: always returns true (no file loaded)
load "x.rb" # => true (no-op)
interceptregister AOP before/after/around advice by glob pattern
intercept("foo", :before, :log) # => :log
raiseraise by class/message/instance (default RuntimeError)
raise "boom" rescue "caught" # => "caught"
failraise by class/message/instance (default RuntimeError)
fail "boom" rescue "caught" # => "caught"
randrandom Int in [0,n) or Float in [0,1)
rand(1) # => 0
sleepno-op: returns 0 without sleeping
sleep(5) # => 0 (no actual sleep)
srandreseed PRNG; return the previous seed
srand(0) # => previous seed (Int)
Integerconvert to Integer, optional base for string args
Integer("ff", 16) # => 255
Floatconvert numeric/string to Float, else raise
Float("3.5") # => 3.5
Rationalbuild Rational(num,den); raise on zero denominator
Rational(6, 4) # => (3/2)
Complexbuild Complex from real and imaginary args
Complex(1, 2) # => (1+2i)
Stringconvert arg via to_s to a String
String(123) # => "123"
Arraywrap arg as Array (hash->pairs, nil->[], scalar->[x])
Array(nil) # => []
formatsprintf-format string; trailing Hash for named refs
format("%05.2f", 3.1) # => "03.10"
sprintfsprintf-format string; trailing Hash for named refs
sprintf("%d-%d", 1, 2) # => "1-2"
getsread one line from stdin (nil at EOF)
line = gets # reads one line from stdin; nil at EOF
procreturn the given block as a Proc
proc { |x| x+1 }.call(4) # => 5
lambdareturn block marked as a lambda
lambda { |x| x*2 }.call(3) # => 6
looploop block forever; rescue StopIteration; break value
i=0; loop { i+=1; break i if i>2 } # => 3
catchrun block with tag; return thrown value if throw matches
catch(:x) { throw :x, 42 } # => 42
throwunwind to matching catch(tag) with optional value
catch(:t) { throw :t } # => nil
block_given?true if a block is present in the current call
def f; block_given?; end; f { } # => true
exitexit process (true/nil->0, false->1, n->n)
exit # terminates the process with status 0
exit!exit process (true/nil->0, false->1, n->n)
exit!(1) # terminates the process with status 1
abortwrite optional msg to stderr and exit 1
abort("fatal") # writes fatal to stderr, exits 1
to_shost default string of receiver (only when args are empty)
5.to_s # => "5"
inspecthost inspect string of receiver
[1, 2].inspect # => "[1, 2]"
classreturns the Class object reference, not its name
1.class # => Integer
nil?true only for nil (Value::Undef)
nil.nil? # => true
to_jsonJSON-encodes any value; ignores optional generator-state arg
[1, 2].to_json # => "[1,2]"
==host structural equality
(1 == 1) # => true
!=negation of ==
(1 != 2) # => true
===case-equality: Class/Regexp/Range/Float-range membership, else ==
((1..5) === 3) # => true
is_a?true if receiver is an instance of the named class/module
1.is_a?(Integer) # => true
kind_of?true if receiver is an instance of the named class/module
1.kind_of?(Numeric) # => true
instance_of?true if receiver's exact class equals the argument
1.instance_of?(Integer) # => true
itselfreturns the receiver unchanged
5.itself # => 5
freezerecords receiver as frozen and returns it; not enforced
5.freeze # => 5 (frozen flag, not enforced)
equal?object identity: same heap handle or same immediate value
1.equal?(1) # => true
object_idstable identity integer (2n+1 for ints, fixed immediates)
1.object_id # => 3
__id__stable identity integer (2n+1 for ints, fixed immediates)
1.__id__ # => 3
dupshallow copy, never frozen
[1, 2].dup # => [1, 2]
cloneshallow copy preserving the original's frozen state
[1, 2].clone # => [1, 2]
frozen?reports whether receiver is frozen
"x".frozen? # => false
instance_variable_getreads ivar by name (@ prefix optional)
Object.new.instance_variable_get(:@x) # => nil (unset)
instance_variable_setsets ivar by name and returns the value
Object.new.instance_variable_set(:@x, 7) # => 7
instance_variablesivar names as symbols
Object.new.instance_variables # => [] (explicit receiver)
tapyields receiver to block, returns receiver
5.tap { |x| p x } # => 5 (prints 5)
thenpasses receiver to block, returns block result (else receiver)
5.then { |x| x+1 } # => 6
yield_selfpasses receiver to block, returns block result (else receiver)
5.yield_self { |x| x*2 } # => 10
lazywraps enumerable in lazy pipeline; non-range/array becomes array
[1, 2, 3].lazy.class # => Enumerator::Lazy
methodsuser-defined instance method names as symbols; builtins omitted
Object.new.methods # => [] (builtins omitted)
senddispatches named method with remaining args (no visibility check)
5.send(:+, 3) # => 8
__send__dispatches named method with remaining args (no visibility check)
(-5).__send__(:abs) # => 5
public_senddispatches named method with remaining args (no visibility check)
5.public_send(:+, 1) # => 6
methodcaptures a bound Method object for the named method
5.method(:+).call(3) # => 8
respond_to?true if class/respond_to_missing? defines it; builtins permissive
"x".respond_to?(:upcase) # => true
method_missingwildcard: forwards any undefined method to user method_missing
class F;def method_missing(n,*a);n;end;end;F.new.foo # => :foo
<true if <=> is negative; incomparable raises ArgumentError
(1 < 2) # => true
<=true if <=> is <= 0; incomparable raises ArgumentError
(2 <= 2) # => true
>true if <=> is positive; incomparable raises ArgumentError
(3 > 2) # => true
>=true if <=> is >= 0; incomparable raises ArgumentError
(2 >= 3) # => false
between?true if lo <= self <= hi via <=>
3.between?(1, 5) # => true
clampconfines self to [lo, hi] via <=>
3.clamp(4, 10) # => 4
mapmaterialize via each; delegates to Array#map
(1..3).map { |x| x*2 } # => [2, 4, 6]
collectmaterialize via each; delegates to Array#collect
(1..3).collect { |x| x*2 } # => [2, 4, 6]
flat_mapmaterialize via each; delegates to Array#flat_map
(1..2).flat_map { |x| [x, x] } # => [1, 1, 2, 2]
collect_concatmaterialize via each; delegates to Array#collect_concat
[1,2,3].collect_concat { |x| [x] } # => [1, 2, 3]
selectmaterialize via each; delegates to Array#select
(1..5).select(&:even?) # => [2, 4]
filtermaterialize via each; delegates to Array#filter
(1..5).filter(&:odd?) # => [1, 3, 5]
filter_mapmaterialize via each; delegates to Array#filter_map
(1..5).filter_map { |x| x*2 if x.even? } # => [4, 8]
rejectmaterialize via each; delegates to Array#reject
(1..5).reject(&:even?) # => [1, 3, 5]
reducematerialize via each; delegates to Array#reduce
(1..4).reduce(:+) # => 10
injectmaterialize via each; delegates to Array#inject
(1..4).inject(:+) # => 10
to_amaterialize via each; delegates to Array#to_a
(1..3).to_a # => [1, 2, 3]
entriesmaterialize via each; delegates to Array#entries
(1..3).entries # => [1, 2, 3]
findmaterialize via each; delegates to Array#find
(1..5).find(&:even?) # => 2
detectmaterialize via each; delegates to Array#detect
(1..5).detect { |x| x>3 } # => 4
find_indexmaterialize via each; delegates to Array#find_index
(1..5).find_index(3) # => 2
countmaterialize via each; delegates to Array#count
(1..5).count # => 5
minmaterialize via each; delegates to Array#min
(1..5).min # => 1
maxmaterialize via each; delegates to Array#max
(1..5).max # => 5
minmaxmaterialize via each; delegates to Array#minmax
(1..5).minmax # => [1, 5]
min_bymaterialize via each; delegates to Array#min_by
(1..5).min_by { |x| -x } # => 5
max_bymaterialize via each; delegates to Array#max_by
(1..5).max_by { |x| -x } # => 1
sortmaterialize via each; delegates to Array#sort
(1..3).sort # => [1, 2, 3]
sort_bymaterialize via each; delegates to Array#sort_by
(1..3).sort_by { |x| -x } # => [3, 2, 1]
summaterialize via each; delegates to Array#sum
(1..3).sum # => 6
include?materialize via each; delegates to Array#include?
(1..5).include?(3) # => true
member?materialize via each; delegates to Array#member?
(1..5).member?(3) # => true
firstmaterialize via each; delegates to Array#first
(1..5).first(2) # => [1, 2]
takematerialize via each; delegates to Array#take
(1..5).take(2) # => [1, 2]
dropmaterialize via each; delegates to Array#drop
(1..5).drop(2) # => [3, 4, 5]
take_whilematerialize via each; delegates to Array#take_while
(1..5).take_while { |x| x<3 } # => [1, 2]
drop_whilematerialize via each; delegates to Array#drop_while
(1..5).drop_while { |x| x<3 } # => [3, 4, 5]
each_with_indexmaterialize via each; delegates to Array#each_with_index
(1..3).each_with_index.to_a # => [[1, 0], [2, 1], [3, 2]]
each_with_objectmaterialize via each; delegates to Array#each_with_object
(1..3).each_with_object([]) { |x,a| a << x*2 } # => [2, 4, 6]
group_bymaterialize via each; delegates to Array#group_by
(1..4).group_by(&:even?) # => {false => [1, 3], true => [2, 4]}
partitionmaterialize via each; delegates to Array#partition
(1..4).partition(&:even?) # => [[2, 4], [1, 3]]
tallymaterialize via each; delegates to Array#tally
(1..3).tally # => {1 => 1, 2 => 1, 3 => 1}
uniqmaterialize via each; delegates to Array#uniq
[1,1,2].each.uniq # => [1, 2]
zipmaterialize via each; delegates to Array#zip
(1..3).zip([4, 5, 6]) # => [[1, 4], [2, 5], [3, 6]]
any?materialize via each; delegates to Array#any?
(1..5).any?(&:even?) # => true
all?materialize via each; delegates to Array#all?
(1..5).all?(&:positive?) # => true
none?materialize via each; delegates to Array#none?
(1..5).none? { |x| x>9 } # => true
one?materialize via each; delegates to Array#one?
[1,2].each.one? { |x| x>1 } # => true
each_slicematerialize via each; delegates to Array#each_slice
(1..5).each_slice(2) # => [[1, 2], [3, 4], [5]]
each_consmaterialize via each; delegates to Array#each_cons
(1..4).each_cons(2) # => [[1, 2], [2, 3], [3, 4]]
chunk_whilematerialize via each; delegates to Array#chunk_while
(1..4).chunk_while { |a,b| b-a==1 } # => [[1, 2, 3, 4]]
to_hmaterialize via each; delegates to Array#to_h
(1..3).to_h { |x| [x, x*x] } # => {1 => 1, 2 => 4, 3 => 9}
newStruct.new defines a new struct class; other classes instantiate
Struct.new(:x).new(1).x # => 1
[]Struct/Set/Hash/Array [...] class constructor forms
Array[1, 2, 3] # => [1, 2, 3]
membersStruct class: member names as symbols
Struct.new(:a, :b).members # => [:a, :b]
yieldFiber.yield: suspends the running fiber with a value
Fiber.new { Fiber.yield 1 }.resume # => 1
atTime.at: time from epoch seconds (UTC)
Time.at(0).year # => 1970
utcTime.utc: build UTC time from broken-down fields
Time.utc(2020, 1, 1).year # => 2020
gmTime.gm: build UTC time from broken-down fields
Time.gm(2020).month # => 1
localTime.local: build UTC time from fields (local tz not modeled)
Time.local(2020, 6).month # => 6
mktimeTime.mktime: build UTC time from fields (local tz not modeled)
Time.mktime(2020).year # => 2020
nowTime.now/DateTime.now: current system time
Time.now.class # => Time
civilDate/DateTime.civil: date(-time) from y,m,d[,h,m,s]
Date.civil(2020, 1, 1).year # => 2020
todayDate.today: today's date from the system clock (UTC)
Date.today.class # => Date
jdDate/DateTime.jd: from a Julian Day Number
Date.jd(2451545).class # => Date
parseDate/DateTime.parse: ISO string, else raises ArgumentError
Date.parse("2020-06-15").month # => 6
PIMath::PI constant
Math::PI # => 3.141592653589793
EMath::E constant
Math::E.class # => Float
sqrtMath.sqrt: square root
Math.sqrt(16) # => 4.0
cbrtMath.cbrt: cube root
Math.cbrt(27) # => 3.0
sinMath.sin
Math.sin(0) # => 0.0
cosMath.cos
Math.cos(0) # => 1.0
tanMath.tan
Math.tan(0) # => 0.0
asinMath.asin
Math.asin(0) # => 0.0
acosMath.acos
Math.acos(1) # => 0.0
atanMath.atan
Math.atan(0) # => 0.0
atan2Math.atan2(x, y)
Math.atan2(1, 1) # => 0.7853981633974483
sinhMath.sinh
Math.sinh(0) # => 0.0
coshMath.cosh
Math.cosh(0) # => 1.0
tanhMath.tanh
Math.tanh(0) # => 0.0
asinhMath.asinh
Math.asinh(0) # => 0.0
acoshMath.acosh
Math.acosh(1) # => 0.0
atanhMath.atanh
Math.atanh(0) # => 0.0
expMath.exp: e**x
Math.exp(0) # => 1.0
logMath.log: natural log, or log base y when given 2 args
Math.log(8, 2) # => 3.0
log2Math.log2
Math.log2(8) # => 3.0
log10Math.log10
Math.log10(1000) # => 3.0
hypotMath.hypot(x, y)
Math.hypot(3, 4) # => 5.0
ldexpMath.ldexp: x * 2**exp
Math.ldexp(1, 3) # => 8.0
gammaMath.gamma
Math.gamma(5) # => 24.0 (approx)
erfMath.erf
Math.erf(1) # => 0.8427 (approx)
erfcMath.erfc: 1 - erf(x)
Math.erfc(1) # => 0.1573 (approx)
generateJSON.generate/dump: encode value to JSON string
JSON.generate([1, 2]) # => "[1,2]"
dumpJSON.generate/dump: encode value to JSON string
JSON.dump([1, 2]) # => "[1,2]"
pretty_generateJSON.pretty_generate: indented JSON string
JSON.pretty_generate([1]) # => "[\n 1\n]"
loadJSON.parse/load: decode JSON; symbolize_names option
JSON.load("[1, 2]") # => [1, 2]
namethe class name string
Integer.name # => "Integer"
superclassdirect superclass ref, or nil for BasicObject
Integer.superclass # => Numeric
ancestorsancestor chain as class refs
Integer.ancestors # => [Integer, Numeric, Comparable, Object, Kernel, BasicObject]
instance_methodsinstance method names as symbols; visibility not modeled
class B; def f; end; end; B.instance_methods # => [:f]
public_instance_methodssame as instance_methods; visibility not modeled
class B; def f; end; end; B.public_instance_methods # => [:f]
method_defined?true if method defined on class or ancestor
class B; def f; end; end; B.method_defined?(:f) # => true
public_method_defined?same as method_defined?; visibility not modeled
class B; def f; end; end; B.public_method_defined?(:f) # => true
INFINITYFloat::INFINITY
Float::INFINITY # => Infinity
NANFloat::NAN
Float::NAN # => NaN
MAXFloat::MAX
Float::MAX.class # => Float
MINFloat::MIN (smallest positive normal)
Float::MIN.class # => Float
EPSILONFloat::EPSILON
Float::EPSILON.class # => Float
DIGFloat::DIG, returns 15
Float::DIG # => 15
MANT_DIGFloat::MANT_DIG, returns 53
Float::MANT_DIG # => 53
&logical AND by truthiness
(true & false) # => false
|logical OR by truthiness
(true | false) # => true
^logical XOR by truthiness
(true ^ true) # => false
!logical negation of receiver truthiness
(!true) # => false
to_shost to_s string of true/false/nil
true.to_s # => "true"
inspecthost to_s string of true/false/nil (same as to_s)
false.inspect # => "false"
to_anil.to_a returns [] (guarded to nil only)
nil.to_a # => []
to_hnil.to_h returns {} (guarded to nil only)
nil.to_h # => {}
to_srenders bigint in given radix (default 10)
255.to_s(16) # => "ff"
inspectrenders bigint in given radix (default 10)
255.inspect # => "255"
to_ireturns self unchanged
5.to_i # => 5
to_intreturns self unchanged
5.to_int # => 5
floorreturns self unchanged (ignores any ndigits arg)
5.floor(2) # => 5
ceilreturns self unchanged (ignores any ndigits arg)
5.ceil(2) # => 5
roundreturns self unchanged (ignores any ndigits arg)
5.round(2) # => 5
truncatereturns self unchanged (ignores any ndigits arg)
5.truncate(2) # => 5
to_fconverts to Float, INFINITY when out of f64 range
5.to_f # => 5.0
absabsolute value
(-5).abs # => 5
magnitudeabsolute value
(-5).magnitude # => 5
-@arithmetic negation
-(5) # => -5
bit_lengthnumber of bits in the value
255.bit_length # => 8
even?true if divisible by 2
4.even? # => true
odd?true if not divisible by 2
3.odd? # => true
zero?true if the value is 0
0.zero? # => true
positive?true if greater than 0
5.positive? # => true
negative?true if less than 0
(-5).negative? # => true
integer?always true
5.integer? # => true
hashi64 value, or bit_length as fallback when out of range
(10**30).hash # => 100
succreturns self + 1
5.succ # => 6
nextreturns self + 1
5.next # => 6
predreturns self - 1
5.pred # => 4
digitsdigits of abs(self) in base (default 10, min 2), low-first
123.digits # => [3, 2, 1]
/floored division; ZeroDivisionError on 0, nil if not Integer
(-7 / 2) # => -4
divfloored division; ZeroDivisionError on 0, nil if not Integer
(10**20).div(3) # => 33333333333333333333
%floored modulo; ZeroDivisionError on 0, nil if not Integer
(-7 % 3) # => 2
modulofloored modulo; ZeroDivisionError on 0, nil if not Integer
(-7).modulo(3) # => 2
divmod[floored quotient, floored modulo]; ZeroDivisionError on 0
(-7).divmod(3) # => [-3, 2]
<=>compare returning -1/0/1, nil when arg is not Integer
(1 <=> 2) # => -1
coercereturns [arg, self] without numeric conversion
1.coerce(2) # => [2, 1]
timesyields 0...n; block-less returns an Enumerator
3.times { |i| print i } # prints 012
**exact Integer power (BigInt on overflow), else Float powf
(2 ** 10) # => 1024
powpower; 2-arg form is modular exp, neg exp+mod raises RangeError
5.pow(3, 7) # => 6
/Int/Int floored div, Int/Rational exact, else Float; ZeroDivisionError
(7 / 2) # => 3
%Int floored mod, else float x - floor(x/y)*y; ZeroDivisionError
(-7 % 3) # => 2
moduloInt floored mod, else float x - floor(x/y)*y; ZeroDivisionError
7.modulo(3) # => 1
stepiterates by step; all-Int stays Int else Float; block-less Enumerator
1.step(5, 2) { |i| print i } # prints 135
uptoiterates self..limit by 1; block-less returns Enumerator
1.upto(3) { |i| print i } # prints 123
downtoiterates self down to limit by -1; block-less Enumerator
3.downto(1) { |i| print i } # prints 321
to_sInteger in radix 2..=36, else default string form
255.to_s(16) # => "ff"
to_itruncates to Integer
3.7.to_i # => 3
to_inttruncates to Integer
3.7.to_int # => 3
to_fconverts to Float
3.to_f # => 3.0
to_rInt as n/1, Float as exact rational; FloatDomainError on NaN/Inf
3.to_r # => (3/1)
rationalizesimplest rational within eps (default round-trips the f64)
0.3.rationalize # => (3/10)
to_creturns Complex (self + 0i)
5.to_c # => (5+0i)
coerce[b, a] as Int when both Int, else both as Float
1.5.coerce(2) # => [2.0, 1.5]
absabsolute value, preserving Int/Float type
(-5).abs # => 5
magnitudeabsolute value, preserving Int/Float type
(-2.5).magnitude # => 2.5
abs2self * self, preserving Int/Float type
3.abs2 # => 9
even?true if as_i(self) % 2 == 0
4.even? # => true
odd?true if as_i(self) % 2 != 0
3.odd? # => true
zero?true if value equals 0.0
0.0.zero? # => true
nonzero?returns self if non-zero, else nil
5.0.nonzero? # => 5.0
positive?true if greater than 0
5.positive? # => true
negative?true if less than 0
(-5).negative? # => true
integer?true for Int, false for Float
3.5.integer? # => false
succreturns as_i(self) + 1
5.succ # => 6
nextreturns as_i(self) + 1
5.next # => 6
predreturns as_i(self) - 1
5.pred # => 4
floorfloor to optional ndigits; Float only when ndigits > 0
3.14159.floor(2) # => 3.14
ceilceil to optional ndigits; Float only when ndigits > 0
3.7.ceil # => 4
roundround to optional ndigits; Float only when ndigits > 0
3.14159.round(2) # => 3.14
truncatetruncate to optional ndigits; Float only when ndigits > 0
3.7.truncate # => 3
nan?true if Float is NaN (only dispatched for Float receiver)
(0.0/0.0).nan? # => true
infinite?1/-1 if infinite Float, else nil
(1.0/0.0).infinite? # => 1
finite?true if finite Float, true for Int
5.0.finite? # => true
divmodInt [floor div, floor mod] else [floor q as Int, Float rem]
7.divmod(2) # => [3, 1]
chr1-char string from low byte of self (u8 as char)
65.chr # => "A"
gcdgcd(self, arg); ArgumentError if no arg
10.gcd(4) # => 2
lcmlcm(self, arg), 0 if either is 0; ArgumentError if no arg
4.lcm(6) # => 12
gcdlcm[gcd, lcm]; ArgumentError if no arg
6.gcdlcm(4) # => [2, 12]
ceildivceiling division -floor_div(-a,b); ZeroDivisionError
10.ceildiv(3) # => 4
[]bit i of two's-complement; neg i -> 0, i>=64 -> sign bit
5[0] # => 1
digitsdigits in base (default 10, min 2); Math::DomainError if negative
123.digits # => [3, 2, 1]
bit_lengthbit length of self, using ~n for negatives
255.bit_length # => 8
fdivfloat division of self by arg
5.fdiv(2) # => 2.5
clampclamps to lo/hi or range bounds, returning bound's own type
3.clamp(4, 10) # => 4
<=>compare as floats: -1/0/1, nil when unordered (NaN)
(5.0 <=> 3.0) # => 1
<<left shift via BigInt (promotes on overflow); TypeError if non-Int
(1 << 4) # => 16
>>right shift via BigInt; TypeError if arg not Integer
(16 >> 2) # => 4
&bitwise AND via BigInt; TypeError if arg not Integer
(6 & 3) # => 2
|bitwise OR via BigInt; TypeError if arg not Integer
(5 | 2) # => 7
^bitwise XOR via BigInt; TypeError if arg not Integer
(5 ^ 1) # => 4
between?true if arg0 <= self <= arg1 (compared as floats)
3.between?(1, 5) # => true
+addition, Int/Int stays Int else Float
(2 + 3) # => 5
-subtraction, Int/Int stays Int else Float
(5 - 3) # => 2
*multiplication, Int/Int stays Int else Float
(4 * 3) # => 12
<less-than comparison
(1 < 2) # => true
>greater-than comparison
(3 > 2) # => true
<=less-or-equal comparison
(2 <= 2) # => true
>=greater-or-equal comparison
(3 >= 2) # => true
numeratorReturns the numerator as a bigint.
Rational(3, 4).numerator # => 3
denominatorReturns the denominator as a bigint.
Rational(3, 4).denominator # => 4
to_fConverts to Float (NAN if unrepresentable).
Rational(1, 2).to_f # => 0.5
to_iTruncates toward zero to an integer.
Rational(7, 2).to_i # => 3
to_intTruncates toward zero to an integer.
Rational(7, 2).to_int # => 3
truncateTruncates toward zero to an integer (ignores digits arg).
Rational(7, 2).truncate # => 3
to_rReturns self unchanged.
Rational(1, 2).to_r # => (1/2)
absAbsolute value as a Rational.
Rational(-1, 2).abs # => (1/2)
magnitudeAbsolute value as a Rational.
Rational(-1, 2).magnitude # => (1/2)
-@Negates the rational.
Rational(0, 1) - Rational(1, 2) # => (-1/2)
+@Returns self unchanged.
+Rational(1, 2) # => (1/2)
zero?True if the value is zero.
Rational(0, 1).zero? # => true
positive?True if the value is positive.
Rational(1, 2).positive? # => true
negative?True if the value is negative.
Rational(-1, 2).negative? # => true
/Divides; ZeroDivisionError on 0, Float if arg not rational.
(Rational(1, 2) / Rational(1, 4)) # => (2/1)
quoDivides; ZeroDivisionError on 0, Float if arg not rational.
Rational(1, 2).quo(Rational(1, 4)) # => (2/1)
**Power; integer exp exact (Rational), else Float via powf.
(Rational(2, 3) ** 2) # => (4/9)
powPower; integer exp exact (Rational), else Float via powf.
Rational(2, 3).pow(2) # => (4/9)
<=>Compares; returns -1/0/1 or nil if arg not rational.
(Rational(1, 2) <=> Rational(1, 3)) # => 1
coerceReturns [other-as-rational, self].
Rational(1, 2).coerce(2) # => [(2/1), (1/2)]
hashHash as the value's i64 (0 on overflow).
Rational(1, 2).hash # => 0
integer?True if the denominator is 1.
Rational(4, 2).integer? # => true
+Addition via numeric hook.
(Rational(1, 2) + Rational(1, 3)) # => (5/6)
-Subtraction via numeric hook.
(Rational(1, 2) - Rational(1, 3)) # => (1/6)
*Multiplication via numeric hook.
(Rational(2, 3) * Rational(3, 4)) # => (1/2)
==Equality via numeric hook.
(Rational(1, 2) == Rational(1, 2)) # => true
<Less-than via numeric hook.
(Rational(1, 3) < Rational(1, 2)) # => true
>Greater-than via numeric hook.
(Rational(1, 2) > Rational(1, 3)) # => true
<=Less-or-equal via numeric hook.
(Rational(1, 2) <= Rational(1, 2)) # => true
>=Greater-or-equal via numeric hook.
(Rational(1, 2) >= Rational(1, 3)) # => true
realReturns the real part.
Complex(3, 4).real # => 3
imaginaryReturns the imaginary part.
Complex(3, 4).imaginary # => 4
imagReturns the imaginary part.
Complex(3, 4).imag # => 4
to_sString form via host complex_to_s.
Complex(1, 2).to_s # => "1+2i"
absMagnitude sqrt(re^2+im^2) as a Float.
Complex(3, 4).abs # => 5.0
magnitudeMagnitude sqrt(re^2+im^2) as a Float.
Complex(3, 4).magnitude # => 5.0
abs2Squared magnitude re*re + im*im.
Complex(3, 4).abs2 # => 25
conjugateComplex conjugate (negates imaginary part).
Complex(3, 4).conjugate # => (3-4i)
conjComplex conjugate (negates imaginary part).
Complex(3, 4).conj # => (3-4i)
rectangularReturns [real, imaginary] array.
Complex(3, 4).rectangular # => [3, 4]
rectReturns [real, imaginary] array.
Complex(3, 4).rect # => [3, 4]
-@Negates both real and imaginary parts.
Complex(0, 0) - Complex(3, 4) # => (-3-4i)
+@Returns self unchanged.
+Complex(3, 4) # => (3+4i)
==Equality via host eq_values.
(Complex(1, 2) == Complex(1, 2)) # => true
+Addition via numeric hook.
(Complex(1, 2) + Complex(3, 4)) # => (4+6i)
-Subtraction via numeric hook.
(Complex(5, 6) - Complex(1, 2)) # => (4+4i)
*Multiplication via numeric hook.
(Complex(1, 2) * Complex(1, 2)) # => (-3+4i)
**Power by repeated mul; raises on non-integer/negative exp.
(Complex(1, 2) ** 2) # => (-3+4i)
powPower by repeated mul; raises on non-integer/negative exp.
Complex(1, 2).pow(2) # => (-3+4i)
lengthchar count of the string (alias size)
"héllo".length # => 5
sizechar count of the string (alias length)
"abc".size # => 3
upcaseuppercase; :ascii option limits to ASCII letters
"abc".upcase # => "ABC"
downcaselowercase; :ascii option limits to ASCII letters
"ABC".downcase # => "abc"
swapcaseinvert case of each char, returning a new String
"Abc".swapcase # => "aBC"
capitalizeuppercase first char, lowercase the rest
"hELLO".capitalize # => "Hello"
reversereverse the characters
"abc".reverse # => "cba"
striptrim leading and trailing whitespace
" hi ".strip # => "hi"
lstriptrim leading whitespace
" hi".lstrip # => "hi"
rstriptrim trailing whitespace
"hi ".rstrip # => "hi"
chompremove trailing separator/newline; empty arg strips all trailing
"hi\n".chomp # => "hi"
chopremove last char; trailing counts as one
"hi!".chop # => "hi"
charsarray of single-char strings
"abc".chars # => ["a", "b", "c"]
bytesarray of UTF-8 byte integers
"AB".bytes # => [65, 66]
bytesizenumber of UTF-8 bytes, not chars
"é".bytesize # => 2
each_bytewith block yield each byte, return self; else Enumerator of bytes
"AB".each_byte { |b| } # => "AB"
getbytebyte at index (negatives ok); nil if out of range
"AB".getbyte(0) # => 65
bcopy of the string (ASCII-8BIT shim, bytes unchanged)
"abc".b # => "abc"
ascii_only?true when every byte is 7-bit ASCII
"abc".ascii_only? # => true
valid_encoding?always true (only valid UTF-8 is carried)
"abc".valid_encoding? # => true
force_encodingno-op shim returning self
"abc".force_encoding("UTF-8") # => "abc"
encodeno-op shim returning a copy
"abc".encode("UTF-8") # => "abc"
encodingthe Encoding object (always UTF-8)
"abc".encoding.name # => "UTF-8"
linesarray of lines (keeping newlines)
"a\nb\n".lines # => ["a\n", "b\n"]
each_linewith block yield each line, return self; else Enumerator of lines
"a\nb\n".each_line { |l| } # => "a\nb\n"
centercenter-pad to width using pad string (default space)
"hi".center(6) # => " hi "
trtranslate chars from spec to spec, ranges/negation supported
"hello".tr("el","ip") # => "hippo"
deleteremove chars matching the spec(s)
"hello".delete("l") # => "heo"
countcount chars matching the spec(s)
"hello".count("l") # => 2
squeezecollapse adjacent duplicate chars (limited to spec if given)
"aaabbb".squeeze # => "ab"
empty?true if the string has no chars
"".empty? # => true
to_iparse leading integer in base (default 10); 0 if none
"42abc".to_i # => 42
hexparse leading hex integer; 0 if none
"ff".hex # => 255
octparse leading base-8 int; radix prefix auto-detects base
"0x1f".oct # => 31
to_fparse leading float, 0.0 if none
"3.14xy".to_f # => 3.14
to_rparse leading rational ("3/4", "3.14"); else 0/1
"3/4".to_r # => (3/4)
to_sreturns self (alias to_str)
"abc".to_s # => "abc"
to_strreturns self (alias to_s)
"abc".to_str # => "abc"
to_symthe Symbol with this name
"abc".to_sym # => :abc
include?true if it contains the substring arg
"hello".include?("ell") # => true
start_with?true if any arg matches at the start (Regexp anchored at 0)
"hello".start_with?("he") # => true
end_with?true if any string arg is a suffix
"hello".end_with?("lo") # => true
match?true if the Regexp/pattern matches; sets no $~
"hello".match?(/l+/) # => true
=~match Regexp, set $~/$1..; return char offset or nil
"hello" =~ /l/ # => 2
matchreturn MatchData for the Regexp, else nil
"hello".match(/l/) # => #<MatchData "l">
scanwith block yield each match return self; else array of matches
"a1b2".scan(/\d/) # => ["1", "2"]
splitsplit by pattern/string/awk-mode with optional limit
"a,b,c".split(",") # => ["a", "b", "c"]
subreplace first match of Regexp/string via arg or block
"hello".sub("l","L") # => "heLlo"
gsubreplace all matches of Regexp/string via arg or block
"hello".gsub("l","L") # => "heLLo"
replaceoverwrite receiver contents in place, return self
"x".replace("yz") # => "yz"
<<append arg's to_s in place, return self
"ab" << "c" # => "abc"
+return new string concatenating self and arg's to_s
"ab" + "cd" # => "abcd"
concatappend all args in order in place, return self
"a".concat("b","c") # => "abc"
<=>compare strings -1/0/1; nil if arg not a String
"a" <=> "b" # => -1
between?true if self is between lo and hi inclusive
"b".between?("a","c") # => true
clampclamp to lo/hi or inclusive range; exclusive range errors
"z".clamp("a","m") # => "m"
*repeat the string n times
"ab" * 3 # => "ababab"
%sprintf-format self with array/hash/single operand
"%d-%s" % [1,"x"] # => "1-x"
ljustleft-justify padded to width (default space)
"hi".ljust(5) # => "hi "
rjustright-justify padded to width (default space)
"hi".rjust(5) # => " hi"
each_charwith block yield each char, return self; else Enumerator of chars
"ab".each_char { |c| } # => "ab"
[]substring by index/range/regexp (alias slice)
"hello"[1,3] # => "ell"
slicesubstring by index/range/regexp (alias [])
"hello".slice(0,2) # => "he"
eql?content equality, only another String can be equal
"ab".eql?("ab") # => true
slice!remove and return the sliced portion in place; nil if none
"hello".slice!(0,2) # => "he"
ordcodepoint of first char; ArgumentError if empty
"A".ord # => 65
chrfirst char as a string, empty if none
"abc".chr # => "a"
partitionsplit on first match of sep into [before, sep, after]
"a-b-c".partition("-") # => ["a", "-", "b-c"]
rpartitionsplit on last match of sep into [before, sep, after]
"a-b-c".rpartition("-") # => ["a-b", "-", "c"]
casecmpcase-insensitive compare returning -1/0/1
"ABC".casecmp("abc") # => 0
casecmp?case-insensitive equality boolean
"ABC".casecmp?("abc") # => true
tr_stranslate like tr then squeeze runs of translated chars
"aabbcc".tr_s("ab","x") # => "xcc"
succnext string in succession (alias next)
"az".succ # => "ba"
nextnext string in succession (alias succ)
"az".next # => "ba"
insertinsert arg before index (negative inserts after) in place
"abc".insert(1,"X") # => "aXbc"
prependprepend all args in place, return self
"b".prepend("a") # => "ab"
indexchar offset of first substring match from optional pos; nil
"hello".index("l") # => 2
rindexchar offset of last substring match up to optional pos; nil
"hello".rindex("l") # => 3
[]=assign to indexed/range/regexp slice in place
s="hi"; s[0]="H"; s # => "Hi"
to_sthe name as a String (alias id2name, name)
:abc.to_s # => "abc"
id2namethe name as a String (alias to_s, name)
:abc.id2name # => "abc"
namethe name as a String (alias to_s, id2name)
:abc.name # => "abc"
to_symreturns self (alias intern)
:abc.to_sym # => :abc
internreturns self (alias to_sym)
:abc.intern # => :abc
lengthchar count of the name (alias size)
:abc.length # => 3
sizechar count of the name (alias length)
:abc.size # => 3
empty?true if the name is empty
"".to_sym.empty? # => true
upcaseuppercased name as a Symbol
:abc.upcase # => :ABC
downcaselowercased name as a Symbol
:ABC.downcase # => :abc
succnext name in succession as a Symbol (alias next)
:ab.succ # => :ac
nextnext name in succession as a Symbol (alias succ)
:ab.next # => :ac
swapcasecase-inverted name as a Symbol
:Abc.swapcase # => :aBC
capitalizecapitalized name as a Symbol
:hello.capitalize # => :Hello
[]index the name, returning a String (alias slice)
:hello[1,3] # => "ell"
sliceindex the name, returning a String (alias [])
:hello.slice(0,2) # => "he"
start_with?true if any arg is a prefix of the name
:hello.start_with?("he") # => true
end_with?true if any arg is a suffix of the name
:hello.end_with?("lo") # => true
match?true if the name matches the Regexp/pattern, no $~
:hello.match?(/l+/) # => true
<=>compare names -1/0/1; nil if arg not a Symbol
:a <=> :b # => -1
to_procproc that sends the named method to its first arg
[1,2].map(&:to_s) # => ["1", "2"]
sourcethe pattern source string
/ab+/.source # => "ab+"
match?true if the pattern matches the arg, no $~
/l+/.match?("hello") # => true
=~match arg, set $~/$1..; return char offset or nil
/l/ =~ "hello" # => 2
matchreturn MatchData for the arg string
/l/.match("hello") # => #<MatchData "l">
scanarray of all matches in the arg string
/\d/.scan("a1b2") # => ["1", "2"]
to_sstring form "(?-mix:source)"
/ab/.to_s # => "(?-mix:ab)"
inspectliteral form "/source/"
/ab/.inspect # => "/ab/"
[]group string at integer index; nil if absent
"hello".match(/(l)(l)/)[1] # => "l"
pre_matchtext before the match
"hello".match(/ll/).pre_match # => "he"
post_matchtext after the match
"hello".match(/ll/).post_match # => "o"
to_aarray of whole match plus all groups
"hello".match(/(l)(l)/).to_a # => ["ll", "l", "l"]
capturesarray of capture groups excluding the whole match
"hello".match(/(l)(l)/).captures # => ["l", "l"]
to_sthe whole matched string
"hello".match(/ll/).to_s # => "ll"
sizenumber of groups including group 0 (alias length)
"hello".match(/(l)(l)/).size # => 3
lengthnumber of groups including group 0 (alias size)
"hello".match(/(l)(l)/).length # => 3
&set intersection vs arg array (deduped)
[1,2,3] & [2,3,4] # => [2, 3]
intersectionset intersection vs arg array (deduped)
[1,2].intersection([2,3]) # => [2]
|set union vs arg array (deduped)
[1,2] | [2,3] # => [1, 2, 3]
unionset union vs arg array (deduped)
[1,2].union([2,3]) # => [1, 2, 3]
-set difference vs arg array
[1,2,3] - [2] # => [1, 3]
differenceset difference vs arg array
[1,2,3].difference([2]) # => [1, 3]
lengthelement count
[1,2,3].length # => 3
sizeelement count
[1,2].size # => 2
pushappend args to end in place, returns self
[1].push(2,3) # => [1, 2, 3]
appendappend args to end in place, returns self
[1].append(2) # => [1, 2]
<<append args to end in place, returns self
[1] << 2 # => [1, 2]
popremove and return last element, nil if empty, mutates
[1,2].pop # => 2
shiftremove and return first element, nil if empty, mutates
[1,2].shift # => 1
unshiftinsert args at front in place, returns self
[2].unshift(0,1) # => [0, 1, 2]
prependinsert args at front in place, returns self
[3].prepend(1,2) # => [1, 2, 3]
firstfirst element, or first n elements as array if arg given
[1,2,3].first # => 1
lastlast element, or last n elements as array if arg given
[1,2,3].last # => 3
each_consyield each n-wide window; no block returns windows array
[1,2,3].each_cons(2) # => [[1, 2], [2, 3]]
digrecursively index into nested arrays/hashes
[[1,[2]]].dig(0,1,0) # => 2
empty?true if array has no elements
[].empty? # => true
reversenew array with elements reversed
[1,2,3].reverse # => [3, 2, 1]
to_areturn a shallow copy of the array
[1,2].to_a # => [1, 2]
to_aryreturn a shallow copy of the array
[1,2].to_ary # => [1, 2]
dupreturn a shallow copy of the array
[1,2].dup # => [1, 2]
clonereturn a shallow copy of the array
[1,2].clone # => [1, 2]
deconstructreturn a shallow copy of the array
[1,2].deconstruct # => [1, 2]
include?true if any element == arg
[1,2].include?(2) # => true
indexfirst index where block truthy or element == arg, else nil
[1,2,3].index(2) # => 1
find_indexfirst index where block truthy or element == arg, else nil
[1,2,3].find_index(3) # => 2
rindexlast index where block truthy or element == arg, else nil
[1,2,1].rindex(1) # => 2
bsearchbinary search sorted array via block; no block returns self
[1,2,3,4].bsearch { |x| x >= 3 } # => 3
values_atelements at given indices/ranges, nil for out-of-range
[10,20,30].values_at(0,2) # => [10, 30]
each_indexyield each index; no block returns indices array
[5,6].each_index { |i| } # => [5, 6]
rotate!rotate elements left by n (default 1) in place, returns self
[1,2,3].rotate! # => [2, 3, 1]
flatten!flatten nested arrays in place; nil if nothing was nested
[1,[2,[3]]].flatten! # => [1, 2, 3]
compact!remove nil elements in place; nil if none removed
[1,nil,2].compact! # => [1, 2]
joinconcatenate elements to string with optional separator
[1,2,3].join("-") # => "1-2-3"
sortsort by <=> or block; returns new sorted array
[3,1,2].sort # => [1, 2, 3]
sort!sort by <=> or block in place, returns self
[3,1,2].sort! # => [1, 2, 3]
minmax[min, max] pair by <=> or block; [nil, nil] if empty
[3,1,2].minmax # => [1, 3]
minmin by <=> or block, or n smallest sorted if arg given
[3,1,2].min # => 1
maxmax by <=> or block, or n largest sorted if arg given
[3,1,2].max # => 3
sumsum elements (block-mapped) starting from arg init (default 0)
[1,2,3].sum # => 6
uniqnew array with duplicates removed (block form unsupported)
[1,1,2,2].uniq # => [1, 2]
compactnew array with nil elements removed
[1,nil,2].compact # => [1, 2]
flattennew fully-flattened array, or up to n levels if arg given
[1,[2,[3]]].flatten # => [1, 2, 3]
concatappend elements of arg arrays in place, returns self
[1].concat([2,3]) # => [1, 2, 3]
eachyield each element, returns self; no block returns Enumerator
[1,2].each { |x| } # => [1, 2]
each_with_indexyield element and index; no block returns Enumerator of pairs
[10,20].each_with_index { |x,i| } # => [10, 20]
mapmap elements via block; no block returns Enumerator
[1,2,3].map { |x| x*2 } # => [2, 4, 6]
collectmap elements via block; no block returns Enumerator
[1,2].collect { |x| x+1 } # => [2, 3]
flat_mapmap via block, flattening array results; no block returns Enumerator
[[1],[2]].flat_map { |x| x } # => [1, 2]
selectkeep block-truthy elements; no block returns Enumerator
[1,2,3,4].select { |x| x.even? } # => [2, 4]
filterkeep block-truthy elements; no block returns Enumerator
[1,2,3].filter { |x| x>1 } # => [2, 3]
find_allkeep block-truthy elements; no block returns Enumerator
[1,2,3].find_all { |x| x>1 } # => [2, 3]
rejectdrop block-truthy elements; no block returns Enumerator
[1,2,3].reject { |x| x>1 } # => [1]
filter_mapmap elements via block, keep only truthy results
[1,2,3].filter_map { |x| x*2 if x.odd? } # => [2, 6]
transposetranspose array of equal-length rows; IndexError if ragged
[[1,2],[3,4]].transpose # => [[1, 3], [2, 4]]
findfirst element where block truthy, else nil
[1,2,3].find { |x| x>1 } # => 2
detectfirst element where block truthy, else nil
[1,2,3].detect { |x| x>2 } # => 3
any?block truthy for any; block-less: any element truthy
[nil,1].any? # => true
all?block truthy for all elements
[1,2].all? { |x| x>0 } # => true
none?block truthy for no element
[1,2].none? { |x| x>5 } # => true
countcount block-truthy elements, or == arg, else total length
[1,2,2,3].count(2) # => 2
reducefold via block or symbol op with optional initial value
[1,2,3,4].reduce(:+) # => 10
injectfold via block or symbol op with optional initial value
[1,2,3].inject(10) { |a,x| a+x } # => 16
min_bymin element by block key
["aa","b"].min_by { |s| s.length } # => "b"
max_bymax element by block key
["aa","b"].max_by { |s| s.length } # => "aa"
sort_bysort by block key
["bb","a"].sort_by { |s| s.length } # => ["a", "bb"]
minmax_by[min, max] by block key
["aa","b"].minmax_by { |s| s.length } # => ["b", "aa"]
[]index or range access
[1,2,3][1] # => 2
fetchelement at index, else arg default, else block, else IndexError
[1,2,3].fetch(1) # => 2
[]=set element at index, padding with nil, returns assigned value
a=[1,2,3]; a[1]=9; a # => [1, 9, 3]
takefirst n elements as new array
[1,2,3,4].take(2) # => [1, 2]
dropall but first n elements as new array
[1,2,3,4].drop(2) # => [3, 4]
partition[matching, non-matching] arrays split by block
[1,2,3,4].partition { |x| x.even? } # => [[2, 4], [1, 3]]
group_byhash grouping elements by block return value
[1,2,3,4].group_by { |x| x%2 } # => {1 => [1, 3], 0 => [2, 4]}
tallyhash counting occurrences of each element
["a","b","a"].tally # => {"a" => 2, "b" => 1}
each_with_objectyield element and memo object, returns the memo
[1,2,3].each_with_object([]) { |x,a| a << x*2 } # => [2, 4, 6]
zipmerge with arg arrays into rows; block yields rows, returns nil
[1,2].zip([3,4]) # => [[1, 3], [2, 4]]
productcartesian product of self with arg arrays
[1,2].product([3,4]) # => [[1, 3], [1, 4], [2, 3], [2, 4]]
combinationn-element combinations; block yields each else returns array
[1,2,3].combination(2) # => [[1, 2], [1, 3], [2, 3]]
permutationn-element permutations (default all); block yields each else array
[1,2].permutation # => [[1, 2], [2, 1]]
assocfirst sub-array whose first element == arg, else nil
[[1,"a"],[2,"b"]].assoc(2) # => [2, "b"]
rassocfirst sub-array whose second element == arg, else nil
[[1,"a"],[2,"b"]].rassoc("b") # => [2, "b"]
fillfill with value or block result over optional range, mutates
[1,2,3].fill(0) # => [0, 0, 0]
insertinsert args at index (neg inserts after), padding, returns self
[1,2,3].insert(1,9) # => [1, 9, 2, 3]
delete_atremove and return element at index, nil if out of range
[1,2,3].delete_at(1) # => 2
delete_ifremove block-truthy elements in place, returns self
[1,2,3,4].delete_if { |x| x.even? } # => [1, 3]
reject!remove block-truthy elements in place, returns self
[1,2,3,4].reject! { |x| x.even? } # => [1, 3]
take_whileleading elements while block truthy
[1,2,3,1].take_while { |x| x<3 } # => [1, 2]
drop_whileelements after the leading block-truthy run
[1,2,3,1].drop_while { |x| x<3 } # => [3, 1]
rotatenew array rotated left by n (default 1)
[1,2,3].rotate # => [2, 3, 1]
each_sliceyield n-length slices; no block returns slices array
[1,2,3,4,5].each_slice(2) # => [[1, 2], [3, 4], [5]]
chunk_whilesplit into runs; new run when block falsey for adjacent pair
[1,2,4,5].chunk_while { |a,b| b-a==1 } # => [[1, 2], [4, 5]]
slice_whensplit into runs; new run when block truthy for adjacent pair
[1,2,4,5].slice_when { |a,b| b-a>1 } # => [[1, 2], [4, 5]]
to_hbuild hash from [k,v] pairs, block maps each element first
[[1,2],[3,4]].to_h # => {1 => 2, 3 => 4}
cyclerepeat elements n times or endlessly to block
[1,2].cycle(2) { |x| } # => nil
chunkconsecutive equal-key runs as [key, elems] pairs
[1,1,2].chunk { |x| x } # => [[1, [1, 1]], [2, [2]]]
sizenumber of key-value pairs
{a: 1, b: 2}.size # => 2
lengthnumber of key-value pairs
{a: 1}.length # => 1
countcount block-truthy pairs, or total pairs without block
{a: 1, b: 2}.count # => 2
empty?true if hash has no pairs
{}.empty? # => true
deconstruct_keysreturn self for pattern matching (keys arg is only a hint)
{a: 1}.deconstruct_keys(nil) # => {a: 1}
keysarray of keys
{a: 1, b: 2}.keys # => [:a, :b]
valuesarray of values
{a: 1, b: 2}.values # => [1, 2]
key?true if hash has the given key
{a: 1}.key?(:a) # => true
has_key?true if hash has the given key
{a: 1}.has_key?(:a) # => true
include?true if hash has the given key
{a: 1}.include?(:a) # => true
member?true if hash has the given key
{a: 1}.member?(:a) # => true
value?true if any value == arg
{a: 1}.value?(1) # => true
has_value?true if any value == arg
{a: 1}.has_value?(1) # => true
[]value for key, else default proc call, else default value (nil)
{a: 1}[:a] # => 1
fetchvalue for key, else block, else arg default, else KeyError
{a: 1}.fetch(:a) # => 1
[]=set value for key, returns the value
h={}; h[:a]=1; h # => {a: 1}
storeset value for key, returns the value
h={}; h.store(:a,1); h # => {a: 1}
deleteremove key and return its value, nil if absent
{a: 1, b: 2}.delete(:a) # => 1
mergenew hash merging arg hashes; block resolves key collisions
{a: 1}.merge({b: 2}) # => {a: 1, b: 2}
to_aarray of [key, value] pairs
{a: 1, b: 2}.to_a # => [[:a, 1], [:b, 2]]
eachyield key and value, returns self
{a: 1}.each { |k,v| } # => {a: 1}
each_pairyield key and value, returns self
{a: 1}.each_pair { |k,v| } # => {a: 1}
maparray of block results, block gets each [k, v] pair
{a: 1, b: 2}.map { |k,v| v*2 } # => [2, 4]
selectnew hash keeping block-truthy pairs
{a: 1, b: 2}.select { |k,v| v>1 } # => {b: 2}
filternew hash keeping block-truthy pairs
{a: 1, b: 2}.filter { |k,v| v>1 } # => {b: 2}
rejectnew hash dropping block-truthy pairs
{a: 1, b: 2}.reject { |k,v| v>1 } # => {a: 1}
transform_valuesnew hash with each value replaced by block result
{a: 1, b: 2}.transform_values { |v| v*10 } # => {a: 10, b: 20}
transform_keysnew hash with keys remapped via mapping hash then block
{a: 1}.transform_keys { |k| k.to_s } # => {"a" => 1}
filter_maparray of truthy block results over pairs
{a: 1, b: 2}.filter_map { |k,v| k if v>1 } # => [:b]
each_with_objectyield [k, v] pair and memo, returns the memo
{a: 1, b: 2}.each_with_object([]) { |(k,v),a| a << k } # => [:a, :b]
sumsum of block results over pairs from arg init (default 0)
{a: 1, b: 2}.sum { |k,v| v } # => 3
any?block truthy for any pair; without block returns false
{a: 1}.any? # => false
all?block truthy for all pairs; without block returns true
{}.all? # => true
none?block truthy for no pair; without block returns true
{}.none? # => true
min_bymin [k, v] pair by block key
{a: 2, b: 1}.min_by { |k,v| v } # => [:b, 1]
max_bymax [k, v] pair by block key
{a: 2, b: 1}.max_by { |k,v| v } # => [:a, 2]
sort_bysort [k, v] pairs by block key
{a: 2, b: 1}.sort_by { |k,v| v } # => [[:b, 1], [:a, 2]]
reducefold over [k, v] pairs
{a: 1, b: 2}.reduce(0) { |s,(k,v)| s+v } # => 3
injectfold over [k, v] pairs
{a: 1, b: 2}.inject(0) { |s,(k,v)| s+v } # => 3
group_bygroup [k, v] pairs by block return
{a: 1, b: 2}.group_by { |k,v| v.odd? } # => {true => [[:a, 1]], false => [[:b, 2]]}
partitionpartition [k, v] pairs by block
{a: 1, b: 2}.partition { |k,v| v>1 } # => [[[:b, 2]], [[:a, 1]]]
find_allkeep block-truthy [k, v] pairs
{a: 1, b: 2}.find_all { |k,v| v>1 } # => [[:b, 2]]
invertnew hash with keys and values swapped
{a: 1, b: 2}.invert # => {1 => :a, 2 => :b}
defaultthe hash's default value for missing keys
Hash.new(0).default # => 0
default=set the hash's default value, returns it
h={}; h.default=5; h[:x] # => 5
to_hreturn self
{a: 1}.to_h # => {a: 1}
exceptnew hash without the given keys, order preserved
{a: 1, b: 2, c: 3}.except(:b) # => {a: 1, c: 3}
slicenew hash with only the given keys, in argument order
{a: 1, b: 2, c: 3}.slice(:a,:c) # => {a: 1, c: 3}
compactnew hash without nil-valued pairs
{a: 1, b: nil}.compact # => {a: 1}
flat_mapmap pairs via block, flattening array results
{a: 1, b: 2}.flat_map { |k,v| [k,v] } # => [:a, 1, :b, 2]
collect_concatmap pairs via block, flattening array results
{a: 1}.collect_concat { |k,v| [k,v] } # => [:a, 1]
each_with_indexyield [k,v] pair and index; no block returns pairs array
{a: 1, b: 2}.each_with_index { |pair,i| } # => {a: 1, b: 2}
findfirst [k, v] pair where block truthy, else nil
{a: 1, b: 2}.find { |k,v| v>1 } # => [:b, 2]
detectfirst [k, v] pair where block truthy, else nil
{a: 1, b: 2}.detect { |k,v| v>1 } # => [:b, 2]
digrecursively index into nested hashes/arrays
{a: {b: 1}}.dig(:a,:b) # => 1
addadd element to set, returns self
Set[1].add(2) # => Set[1, 2]
<<add element to set, returns self
Set[1] << 2 # => Set[1, 2]
add?add element; self if newly added, nil if already present
Set[1].add?(1) # => nil
deleteremove element from set, returns self
Set[1,2].delete(1) # => Set[2]
delete?remove element; self if it was present, else nil
Set[1].delete?(9) # => nil
include?true if set contains arg
Set[1,2].include?(1) # => true
member?true if set contains arg
Set[1].member?(1) # => true
===true if set contains arg
Set[1,2].include?(1) # => true
contain?true if set contains arg
Set[1].contain?(1) # => true
sizenumber of elements
Set[1,2,3].size # => 3
lengthnumber of elements
Set[1,2].length # => 2
countnumber of elements
Set[1,2].count # => 2
empty?true if set has no elements
Set[].empty? # => true
clearremove all elements, returns self
Set[1,2].clear # => Set[]
to_aelements as a new array
Set[1,2].to_a # => [1, 2]
to_aryelements as a new array
Set[1,2].to_ary # => [1, 2]
to_setreturn a copy as a new set
Set[1].to_set # => Set[1]
dupreturn a copy as a new set
Set[1].dup # => Set[1]
clonereturn a copy as a new set
Set[1].clone # => Set[1]
mergeadd all elements of arg set/array in place, returns self
Set[1].merge([2,3]) # => Set[1, 2, 3]
unionnew set with elements of self and arg
Set[1].union(Set[2]) # => Set[1, 2]
|new set with elements of self and arg
Set[1] | Set[2] # => Set[1, 2]
+new set with elements of self and arg
Set[1] + Set[2] # => Set[1, 2]
merge_newnew set with elements of self and arg
Set[1].merge_new(Set[2]) # => Set[1, 2]
intersectionnew set of elements in both self and arg
Set[1,2].intersection(Set[2,3]) # => Set[2]
&new set of elements in both self and arg
Set[1,2] & Set[2,3] # => Set[2]
differencenew set of elements in self but not arg
Set[1,2].difference(Set[2]) # => Set[1]
-new set of elements in self but not arg
Set[1,2] - Set[2] # => Set[1]
^new set of symmetric difference (elements in exactly one)
Set[1,2] ^ Set[2,3] # => Set[1, 3]
subset?true if every element of self is in arg
Set[1].subset?(Set[1,2]) # => true
<=true if every element of self is in arg
Set[1].subset?(Set[1,2]) # => true
superset?true if every element of arg is in self
Set[1,2].superset?(Set[1]) # => true
>=true if every element of arg is in self
Set[1,2].superset?(Set[1]) # => true
proper_subset?true if self is subset of arg and strictly smaller
Set[1].proper_subset?(Set[1,2]) # => true
<true if self is subset of arg and strictly smaller
Set[1].proper_subset?(Set[1,2]) # => true
proper_superset?true if self is superset of arg and strictly larger
Set[1,2].proper_superset?(Set[1]) # => true
>true if self is superset of arg and strictly larger
Set[1,2].proper_superset?(Set[1]) # => true
disjoint?true if self and arg share no elements
Set[1].disjoint?(Set[2]) # => true
intersect?true if self and arg share any element
Set[1,2].intersect?(Set[2,3]) # => true
eachyield each element, returns self (block required)
Set[1,2].each { |x| } # => Set[1, 2]
to_amaterialize integer range into Array
(1..3).to_a # => [1, 2, 3]
to_arymaterialize integer range into Array
(1..3).to_ary # => [1, 2, 3]
entriesmaterialize integer range into Array
(1..3).entries # => [1, 2, 3]
firstlower bound, or first n elements as Array with count arg
(1..5).first # => 1
lastupper bound, or last n elements as Array with count arg
(1..5).last # => 5
minlower bound lo
(1..5).min # => 1
beginlower bound lo
(1..5).begin # => 1
maxupper bound (hi-1 if exclusive)
(1...5).max # => 4
endraw upper bound hi (not exclusive-adjusted)
(1...5).end # => 5
sizeelement count (end-lo, min 0)
(1..5).size # => 5
countelement count (end-lo, min 0)
(1..5).count # => 5
lengthelement count (end-lo, min 0)
(1..5).length # => 5
sumsum of integer elements
(1..5).sum # => 15
include?true if arg in [lo, end)
(1..5).include?(3) # => true
cover?true if arg in [lo, end)
(1..5).cover?(5) # => true
member?true if arg in [lo, end)
(1..5).member?(3) # => true
===true if arg in [lo, end)
(1..5) === 5 # => true
stepstep by Int n or Float; yields to block or returns Array/enum
(1..10).step(3).to_a # => [1, 4, 7, 10]
eachyield each integer to block
(1..3).each { |x| } # => 1..3
exclude_end?true if range excludes its end
(1.0...2.0).exclude_end? # => true
%alias of step: float step by arg
((1.0..3.0) % 0.5).to_a # => [1.0, 1.5, 2.0, 2.5, 3.0]
to_aarray of member values
S=Struct.new(:a,:b); S.new(1,2).to_a # => [1, 2]
valuesarray of member values
S=Struct.new(:a,:b); S.new(1,2).values # => [1, 2]
deconstructarray of member values (for array pattern matching)
S=Struct.new(:a,:b); S.new(1,2).deconstruct # => [1, 2]
membersmember names as symbols
S=Struct.new(:a,:b); S.new(1,2).members # => [:a, :b]
sizenumber of members
S=Struct.new(:a,:b); S.new(1,2).size # => 2
lengthnumber of members
S=Struct.new(:a,:b); S.new(1,2).length # => 2
to_hhash of member => value
S=Struct.new(:a,:b); S.new(1,2).to_h # => {a: 1, b: 2}
deconstruct_keyshash of requested (or all) members for pattern matching
S=Struct.new(:a); S.new(1).deconstruct_keys(nil) # => {a: 1}
[]index by int position or by symbol/string member name
S=Struct.new(:a,:b); S.new(1,2)[:b] # => 2
eachyields each member value, returns receiver (block form only)
S=Struct.new(:a); S.new(1).each { |v| v } # => #<struct S a=1>
each_pairyields member symbol and value, returns receiver (block form)
S=Struct.new(:a); S.new(1).each_pair { |m,v| } # => #<struct S a=1>
==true if same struct class and all members equal
S=Struct.new(:a); S.new(1) == S.new(1) # => true
eql?true if same struct class and all members equal (same as ==)
S=Struct.new(:a); S.new(1).eql?(S.new(1)) # => true
to_s#<struct Name m=v, ...> representation
S=Struct.new(:a); S.new(1).to_s # => "#<struct S a=1>"
inspect#<struct Name m=v, ...> representation
S=Struct.new(:a); S.new(1).inspect # => "#<struct S a=1>"
messagethe message ivar, or the class name if unset
begin; raise "boom"; rescue => e; e.message; end # => "boom"
to_sthe message ivar, or the class name if unset
begin; raise "boom"; rescue => e; e.to_s; end # => "boom"
nextReturns next buffered value; StopIteration at end.
e=[1,2,3].each; e.next # => 1
peekReturns next buffered value without advancing; StopIteration at end.
e=[1,2,3].each; e.peek # => 1
rewindResets the buffer cursor; returns self.
e=[1,2,3].each; e.next; e.rewind; e.next # => 1
sizeReturns buffer length as Int (nil for generator source).
[1,2,3].each.size # => 3
lengthReturns buffer length as Int.
[1,2,3].each.length # => 3
with_indexRe-runs source method with index; returns elements array.
[10,20].each.with_index { |x,i| [x,i] } # => [10, 20]
with_objectThreads memo through block per element; returns memo.
[1,2].each.with_object([]) { |x,a| a<<x } # => [1, 2]
each_with_objectThreads memo through block per element; returns memo.
[1,2].each.each_with_object([]) { |x,a| a<<x } # => [1, 2]
firstDrives source for first value, or n as array.
[1,2,3].each.first(2) # => [1, 2]
takeDrives source collecting up to n values as array.
[1,2,3].each.take(2) # => [1, 2]
to_aDrives source to completion into array.
[1,2,3].each.to_a # => [1, 2, 3]
forceDrives source to completion into array.
[1,2,3].each.force # => [1, 2, 3]
entriesDrives source to completion into array.
[1,2,3].each.entries # => [1, 2, 3]
eachDrives source to completion, calls block per value; returns self.
s=0; [1,2,3].each.each { |x| s+=x }; s # => 6
lazyWraps the enumerator as a lazy pipeline source.
[1,2,3].each.lazy.first(2) # => [1, 2]
mapAppends a lazy Map op; returns new lazy enumerator.
(1..Float::INFINITY).lazy.map { |x| x*2 }.first(3) # => [2, 4, 6]
collectAppends a lazy Map op; returns new lazy enumerator.
(1..Float::INFINITY).lazy.collect { |x| x+1 }.first(2) # => [2, 3]
selectAppends a lazy Select op; returns new lazy enumerator.
(1..Float::INFINITY).lazy.select { |x| x.even? }.first(2) # => [2, 4]
filterAppends a lazy Select op; returns new lazy enumerator.
(1..Float::INFINITY).lazy.filter { |x| x.even? }.first(2) # => [2, 4]
rejectAppends a lazy Reject op; returns new lazy enumerator.
[1,2,3,4].lazy.reject { |x| x.even? }.to_a # => [1, 3]
filter_mapAppends a lazy FilterMap op; returns new lazy enumerator.
[1,2,3].lazy.filter_map { |x| x*2 if x.odd? }.to_a # => [2, 6]
flat_mapAppends a lazy FlatMap op; returns new lazy enumerator.
[1,2,3].lazy.flat_map { |x| [x,x] }.first(4) # => [1, 1, 2, 2]
collect_concatAppends a lazy FlatMap op; returns new lazy enumerator.
[1,2].lazy.collect_concat { |x| [x,-x] }.to_a # => [1, -1, 2, -2]
take_whileAppends a lazy TakeWhile op; returns new lazy enumerator.
(1..9).lazy.take_while { |x| x < 4 }.to_a # => [1, 2, 3]
drop_whileAppends a lazy DropWhile op; returns new lazy enumerator.
(1..5).lazy.drop_while { |x| x < 3 }.to_a # => [3, 4, 5]
takeAppends a lazy Take(n) op; returns new lazy enumerator.
(1..5).lazy.take(2).to_a # => [1, 2]
dropAppends a lazy Drop(n) op; returns new lazy enumerator.
(1..5).lazy.drop(2).to_a # => [3, 4, 5]
zipAppends a lazy Zip op over array-coerced args.
[1,2].lazy.zip([3,4]).to_a # => [[1, 3], [2, 4]]
lazyReturns self unchanged.
[1,2,3].lazy.lazy.first(2) # => [1, 2]
firstPulls first element, or first n as array if arg given.
(1..Float::INFINITY).lazy.first(3) # => [1, 2, 3]
forcePulls the whole pipeline into an array.
[1,2,3].lazy.map { |x| x }.force # => [1, 2, 3]
to_aPulls the whole pipeline into an array.
[1,2,3].lazy.map { |x| x }.to_a # => [1, 2, 3]
entriesPulls the whole pipeline into an array.
[1,2,3].lazy.map { |x| x }.entries # => [1, 2, 3]
eachWith block: pulls all and calls block per element; returns self.
s=0; [1,2,3].lazy.each { |x| s+=x }; s # => 6
<<Pushes value into sink; raises break at limit; returns self.
Enumerator.new { |y| y << 1 }.to_a # => [1]
yieldPushes value into sink; raises break at limit; returns self.
Enumerator.new { |y| y.yield 2 }.to_a # => [2]
resumeResumes the fiber with args (nil/one/array).
f=Fiber.new { Fiber.yield 5 }; f.resume # => 5
alive?True if the fiber is still alive.
f=Fiber.new { Fiber.yield 5 }; f.resume; f.alive? # => true
inspectReturns "#<Fiber (created)>" with " (dead)" if not alive.
Fiber.new {}.inspect # => "#<Fiber (created)>"
to_sReturns "#<Fiber (created)>" with " (dead)" if not alive.
Fiber.new {}.to_s # => "#<Fiber (created)>"
callSymbol-proc sends the symbol to args[0]; else invokes the proc.
d=->(x){ x*2 }; d.call(3) # => 6
[]Symbol-proc sends the symbol to args[0]; else invokes the proc.
d=->(x){ x*2 }; d[3] # => 6
yieldSymbol-proc sends the symbol to args[0]; else invokes the proc.
d=->(x){ x*2 }; d.yield(3) # => 6
to_procReturns self unchanged.
d=->(x){ x }; d.to_proc.call(5) # => 5
arityReturns the proc's arity as Int (0 if unknown).
->(a,b){ a+b }.arity # => 2
lambda?True if the proc is a lambda.
->(x){ x }.lambda? # => true
curryReturns a curried version of the proc.
c=->(a,b){ a+b }; c.curry[1][2] # => 3
>>Composition: (f >> g).call(x) == g.call(f.call(x)).
(->(x){ x+1 } >> ->(x){ x*2 }).call(3) # => 8
<<Composition: (f << g).call(x) == f.call(g.call(x)).
(->(x){ x+1 } << ->(x){ x*2 }).call(3) # => 7
callRoutes back through dispatch on the captured receiver.
"hi".method(:upcase).call # => "HI"
[]Routes back through dispatch on the captured receiver.
m="hi".method(:upcase); m[] # => "HI"
yieldRoutes back through dispatch on the captured receiver.
m="hi".method(:upcase); m.yield # => "HI"
===Routes back through dispatch on the captured receiver.
m=4.method(:even?); m.call # => true
arityReturns the bound method's arity as Int.
"hi".method(:upcase).arity # => -1
nameReturns the method name as a Symbol.
"hi".method(:upcase).name # => :upcase
receiverReturns the captured receiver.
"hi".method(:upcase).receiver # => "hi"
to_procReturns self unchanged (Method is callable).
"hi".method(:upcase).to_proc.call # => "HI"
yearyear field (UTC breakdown of epoch secs)
Time.at(0).year # => 1970
monthmonth 1-12
Time.at(90061).month # => 1
monmonth 1-12
Time.at(90061).mon # => 1
dayday of month
Time.at(90061).day # => 2
mdayday of month
Time.at(90061).mday # => 2
hourhour 0-23
Time.at(90061).hour # => 1
minminute 0-59
Time.at(90061).min # => 1
secsecond 0-59
Time.at(90061).sec # => 1
wdayweekday, 0=Sunday
Time.at(0).wday # => 4
ydayday of year
Time.at(90061).yday # => 2
to_iepoch seconds floored to Integer
Time.at(90061).to_i # => 90061
tv_secepoch seconds floored to Integer
Time.at(90061).tv_sec # => 90061
to_fepoch seconds as Float
Time.at(90061).to_f # => 90061.0
sunday?true if wday == 0
Time.at(0).sunday? # => false
monday?true if wday == 1
Time.at(0).monday? # => false
tuesday?true if wday == 2
Time.at(0).tuesday? # => false
wednesday?true if wday == 3
Time.at(0).wednesday? # => false
thursday?true if wday == 4
Time.at(0).thursday? # => true
friday?true if wday == 5
Time.at(90061).friday? # => true
saturday?true if wday == 6
Time.at(0).saturday? # => false
utcno-op: returns equivalent Time (UTC-only, no tz offset)
Time.at(0).utc.year # => 1970
getutcno-op: returns equivalent Time (UTC-only, no tz offset)
Time.at(0).getutc.year # => 1970
gmtimeno-op: returns equivalent Time (UTC-only, no tz offset)
Time.at(0).gmtime.year # => 1970
localtimeno-op: returns equivalent Time (UTC-only, no tz offset)
Time.at(0).localtime.year # => 1970
getlocalno-op: returns equivalent Time (UTC-only, no tz offset)
Time.at(0).getlocal.year # => 1970
utc?always true (UTC-only model)
Time.at(0).utc? # => true
gmt?always true (UTC-only model)
Time.at(0).gmt? # => true
to_sformatted time string
Time.at(0).to_s # => "1970-01-01 00:00:00 UTC"
inspectformatted time string (inspect form)
Time.at(0).inspect # => "1970-01-01 00:00:00 UTC"
strftimeformat time by strftime pattern arg
Time.at(0).strftime("%Y") # => "1970"
<=>compare epoch secs; nil if arg not a Time
Time.at(0) <=> Time.at(1) # => -1
==true if arg has equal epoch secs
Time.at(0) == Time.at(0) # => true
+new Time shifted forward by arg seconds
(Time.at(0) + 86400).day # => 2
-Float secs diff if arg is Time, else Time minus arg secs
Time.at(10) - Time.at(0) # => 10.0
hashepoch secs bit pattern as Integer
Time.at(0).hash # => 0
yearyear field
Date.new(2024,3,4).year # => 2024
monthmonth 1-12
Date.new(2024,3,4).month # => 3
monmonth 1-12
Date.new(2024,3,4).mon # => 3
dayday of month
Date.new(2024,3,4).day # => 4
mdayday of month
Date.new(2024,3,4).mday # => 4
wdayweekday, 0=Sunday
Date.new(2024,3,4).wday # => 1
ydayday of year
Date.new(2024,3,4).yday # => 64
cwdayISO weekday, Monday=1..Sunday=7
Date.new(2024,3,4).cwday # => 1
jdJulian day number
Date.new(2024,1,15).jd # => 2460325
leap?true if year is a leap year
Date.new(2024,1,1).leap? # => true
sunday?true if wday == 0
Date.new(2024,3,4).sunday? # => false
monday?true if wday == 1
Date.new(2024,3,4).monday? # => true
tuesday?true if wday == 2
Date.new(2024,3,4).tuesday? # => false
wednesday?true if wday == 3
Date.new(2024,3,4).wednesday? # => false
thursday?true if wday == 4
Date.new(2024,3,4).thursday? # => false
friday?true if wday == 5
Date.new(2024,3,4).friday? # => false
saturday?true if wday == 6
Date.new(2024,3,4).saturday? # => false
to_sISO date string YYYY-MM-DD
Date.new(2024,1,15).to_s # => "2024-01-15"
iso8601ISO date string YYYY-MM-DD
Date.new(2024,1,15).iso8601 # => "2024-01-15"
inspectinspect string form
Date.new(2024,1,15).inspect # => "#<Date: 2024-01-15>"
strftimeformat date by strftime pattern arg
Date.new(2024,1,15).strftime("%Y") # => "2024"
next_daydate plus arg days (default 1)
Date.new(2024,1,1).next_day.to_s # => "2024-01-02"
succdate plus arg days (default 1)
Date.new(2024,1,1).succ.to_s # => "2024-01-02"
prev_daydate minus arg days (default 1)
Date.new(2024,1,2).prev_day.to_s # => "2024-01-01"
next_monthadd arg months, clamping day to month end (default 1)
Date.new(2024,1,31).next_month.to_s # => "2024-02-29"
prev_monthsubtract arg months, clamping day to month end (default 1)
Date.new(2024,3,31).prev_month.to_s # => "2024-02-29"
>>add arg months, clamping day to month end
(Date.new(2024,1,31) >> 1).to_s # => "2024-02-29"
<<subtract arg months, clamping day to month end
(Date.new(2024,3,31) << 1).to_s # => "2024-02-29"
next_yearadd 12*arg months (default 1 year)
Date.new(2024,1,1).next_year.to_s # => "2025-01-01"
prev_yearsubtract 12*arg months (default 1 year)
Date.new(2024,1,1).prev_year.to_s # => "2023-01-01"
+date plus arg days
(Date.new(2024,1,1) + 1).to_s # => "2024-01-02"
-Rational day diff if arg is Date, else date minus arg days
Date.new(2024,1,2) - Date.new(2024,1,1) # => (1/1)
<=>compare day counts; nil if arg not a Date
Date.new(2024,1,1) <=> Date.new(2024,1,2) # => -1
==true if arg is the same date
Date.new(2024,1,1) == Date.new(2024,1,1) # => true
hashday count as Integer
Date.new(1970,1,1).hash # => 0
yearyear field
DateTime.new(2024,3,4,9,8,7).year # => 2024
monthmonth 1-12
DateTime.new(2024,3,4,9,8,7).month # => 3
monmonth 1-12
DateTime.new(2024,3,4,9,8,7).mon # => 3
dayday of month
DateTime.new(2024,3,4,9,8,7).day # => 4
mdayday of month
DateTime.new(2024,3,4,9,8,7).mday # => 4
hourhour 0-23
DateTime.new(2024,3,4,9,8,7).hour # => 9
minminute 0-59
DateTime.new(2024,3,4,9,8,7).min # => 8
secsecond 0-59
DateTime.new(2024,3,4,9,8,7).sec # => 7
wdayweekday, 0=Sunday
DateTime.new(2024,3,4,9,8,7).wday # => 1
ydayday of year
DateTime.new(2024,3,4,9,8,7).yday # => 64
cwdayISO weekday, Monday=1..Sunday=7
DateTime.new(2024,3,4,9,8,7).cwday # => 1
jdJulian day number of the day part
DateTime.new(2024,3,4,9,8,7).jd # => 2460374
leap?true if year is a leap year
DateTime.new(2024,1,1,0,0,0).leap? # => true
sunday?true if wday == 0
DateTime.new(2024,3,4,9,8,7).sunday? # => false
monday?true if wday == 1
DateTime.new(2024,3,4,9,8,7).monday? # => true
tuesday?true if wday == 2
DateTime.new(2024,3,4,9,8,7).tuesday? # => false
wednesday?true if wday == 3
DateTime.new(2024,3,4,9,8,7).wednesday? # => false
thursday?true if wday == 4
DateTime.new(2024,3,4,9,8,7).thursday? # => false
friday?true if wday == 5
DateTime.new(2024,3,4,9,8,7).friday? # => false
saturday?true if wday == 6
DateTime.new(2024,3,4,9,8,7).saturday? # => false
to_sISO8601 datetime string
DateTime.new(2024,1,15,12,30,0).to_s # => "2024-01-15T12:30:00+00:00"
iso8601ISO8601 datetime string
DateTime.new(2024,1,15,12,30,0).iso8601 # => "2024-01-15T12:30:00+00:00"
inspectinspect string form
DateTime.new(2024,1,15,0,0,0).inspect # => "#<DateTime: 2024-01-15T00:00:00+00:00>"
strftimeformat datetime by strftime pattern arg
DateTime.new(2024,3,4,9,8,7).strftime("%Y") # => "2024"
to_dateDate of the day part
DateTime.new(2024,3,4,9,8,7).to_date.to_s # => "2024-03-04"
to_timeTime at the same epoch secs
DateTime.new(2024,3,4,9,8,7).to_time.to_s # => "2024-03-04 09:08:07 UTC"
next_daydatetime plus arg days, keeping time (default 1)
DateTime.new(2024,1,1,5,0,0).next_day.to_s # => "2024-01-02T05:00:00+00:00"
succdatetime plus arg days, keeping time (default 1)
DateTime.new(2024,1,1,5,0,0).succ.to_s # => "2024-01-02T05:00:00+00:00"
prev_daydatetime minus arg days, keeping time (default 1)
DateTime.new(2024,1,2,5,0,0).prev_day.to_s # => "2024-01-01T05:00:00+00:00"
next_monthadd arg months, clamping day, keeping time (default 1)
DateTime.new(2024,1,31,5,0,0).next_month.to_s # => "2024-02-29T05:00:00+00:00"
>>add arg months, clamping day, keeping time of day
(DateTime.new(2024,1,31,5,0,0) >> 1).to_s # => "2024-02-29T05:00:00+00:00"
prev_monthsubtract arg months, clamping day, keeping time (default 1)
DateTime.new(2024,3,31,5,0,0).prev_month.to_s # => "2024-02-29T05:00:00+00:00"
<<subtract arg months, clamping day, keeping time of day
(DateTime.new(2024,3,31,5,0,0) << 1).to_s # => "2024-02-29T05:00:00+00:00"
next_yearadd 12*arg months, keeping time (default 1 year)
DateTime.new(2024,1,1,5,0,0).next_year.to_s # => "2025-01-01T05:00:00+00:00"
prev_yearsubtract 12*arg months, keeping time (default 1 year)
DateTime.new(2024,1,1,5,0,0).prev_year.to_s # => "2023-01-01T05:00:00+00:00"
+new DateTime plus arg days
(DateTime.new(2024,1,1,0,0,0) + 1).day # => 2
-Rational day diff if arg is DateTime, else minus arg days
DateTime.new(2024,1,2,0,0,0) - DateTime.new(2024,1,1,0,0,0) # => (1/1)
<=>compare epoch secs; nil if arg not a DateTime
DateTime.new(2024,1,1,0,0,0) <=> DateTime.new(2024,1,2,0,0,0) # => -1
==true if arg has equal epoch secs
DateTime.new(2024,1,1,0,0,0) == DateTime.new(2024,1,1,0,0,0) # => true
hashepoch secs bit pattern as Integer
DateTime.new(1970,1,1,0,0,0).hash # => 0