Skip to content

Variables and Types#

Variables#

Basic#

1
my_variable = "Content"

Constant#

1
MY_CONSTANT = "Content"

Discard Variable#

1
2
version                         = '3.2.1'
major_version, minor_version, _ = version.split('.')

Types#

Each types are class. To manipulate variable, you can use methods depending on the type with this syntax:

1
variable.method.method

Example:

1
2
my_string = "Foo Bar"
nb_words  = my_string.split(' ').size #=> 2

nil#

nil is like null of 0 for other language.

1
2
3
4
5
6
7
8
foo = nil
foo.nil? #=> true

foo = 42
foo.nil? #=> false

foo = "bar"
foo.nil? #=> false

String#

String Methods

1
2
3
4
# With single quotes
single_quotes = 'Foo Bar'
# With double quotes
double_quotes = "Foo Bar"

Concat and Interpolation#

The quotes depends on if you want to use a variable on your string:

1
2
single_quotes = 'Foo #{Bar}'                       #=> "Foo #{Bar}"
double_quotes = "single_quotes: #{single_quotes}"  #=> "single_quotes: Foo #{Bar}"

Some examples to add variable into string:

1
2
3
4
foo        = "Foo"           #=> "Foo"
bar        = 42              #=> 42
str_concat = foo + " " + bar #=> `+': no implicit conversion of Integer into String (TypeError)
str_concat = "#{foo} #{bar}" #=> "Foo 42"

The conversion to string is made automatically most of time with Interpolation, but you can explicit it with to_s:

1
2
3
4
foo           = "Foo"                #=> "Foo"
bar           = 42                   #=> 42
str_concatexp = foo + " " + bar.to_s #=> "Foo 42"
str_concat = "#{foo} #{bar}"         #=> "Foo 42"

Methods#

Methods for Querying:

  • Counts:
    • length, size: Returns the count of characters (not bytes).
    • empty?: Returns true if self.length is zero; false otherwise.
    • bytesize: Returns the count of bytes.
    • count: Returns the count of substrings matching given strings.
  • Substrings:
    • #=~: Returns the index of the first substring that matches a given Regexp or other object; returns nil if no match is found.
    • index: Returns the index of the first occurrence of a given substring; returns nil if none found.
    • rindex: Returns the index of the last occurrence of a given substring; returns nil if none found.
    • include?: Returns true if the string contains a given substring; false otherwise.
    • match: Returns a MatchData object if the string matches a given Regexp; nil otherwise.
    • match?: Returns true if the string matches a given Regexp; false otherwise.
    • start_with?: Returns true if the string begins with any of the given substrings.
    • end_with?: Returns true if the string ends with any of the given substrings.
  • Encodings:
    • encoding: Returns the Encoding object that represents the encoding of the string.
    • unicode_normalized?: Returns true if the string is in Unicode normalized form; false otherwise.
    • valid_encoding?: Returns true if the string contains only characters that are valid for its encoding.
    • ascii_only?: Returns true if the string has only ASCII characters; false otherwise.
  • Other:
    • sum: Returns a basic checksum for the string: the sum of each byte.
    • hash: Returns the integer hash code.

Methods for Comparing:

  • #==, #===: Returns true if a given other string has the same content as self.
  • eql?: Returns true if the content is the same as the given other string.
  • #<=>: Returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than self.
  • casecmp: Ignoring case, returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than self.
  • casecmp?: Returns true if the string is equal to a given string after Unicode case folding; false otherwise.

Methods for Modifying a String:

Note

Each of these methods modifies self.

  • Insertion:
    • insert: Returns self with a given string inserted at a given offset.
    • <<: Returns self concatenated with a given string or integer.
  • Substitution:
    • sub!: Replaces the first substring that matches a given pattern with a given replacement string; returns self if any changes, nil otherwise.
    • gsub!: Replaces each substring that matches a given pattern with a given replacement string; returns self if any changes, nil otherwise.
    • succ!, next!: Returns self modified to become its own successor.
    • replace: Returns self with its entire content replaced by a given string.
    • reverse!: Returns self with its characters in reverse order.
    • setbyte: Sets the byte at a given integer offset to a given value; returns the argument.
    • tr!: Replaces specified characters in self with specified replacement characters; returns self if any changes, nil otherwise.
    • tr_s!: Replaces specified characters in self with specified replacement characters, removing duplicates from the substrings that were modified; returns self if any changes, nil otherwise.
  • Casing:
    • capitalize!: Upcases the initial character and downcases all others; returns self if any changes, nil otherwise.
    • downcase!: Downcases all characters; returns self if any changes, nil otherwise.
    • upcase!: Upcases all characters; returns self if any changes, nil otherwise.
    • swapcase!: Upcases each downcase character and downcases each upcase character; returns self if any changes, nil otherwise.
  • Encoding:
    • encode!: Returns self with all characters transcoded from one given encoding into another.
    • unicode_normalize!: Unicode-normalizes self; returns self.
    • scrub!: Replaces each invalid byte with a given character; returns self.
    • force_encoding: Changes the encoding to a given encoding; returns self.
  • Deletion:
    • clear: Removes all content, so that self is empty; returns self.
    • slice!, []=: Removes a substring determined by a given index, start/length, range, regexp, or substring.
    • squeeze!: Removes contiguous duplicate characters; returns self.
    • delete!: Removes characters as determined by the intersection of substring arguments.
    • lstrip!: Removes leading whitespace; returns self if any changes, nil otherwise.
    • rstrip!: Removes trailing whitespace; returns self if any changes, nil otherwise.
    • strip!: Removes leading and trailing whitespace; returns self if any changes, nil otherwise.
    • chomp!: Removes trailing record separator, if found; returns self if any changes, nil otherwise.
    • chop!: Removes trailing whitespace if found, otherwise removes the last character; returns self if any changes, nil otherwise.

Methods for Converting to New String:

Note

Each of these methods returns a new String based on self, often just a modified copy of self.:

  • Extension:
    • *: Returns the concatenation of multiple copies of self,
    • +: Returns the concatenation of self and a given other string.
    • center: Returns a copy of self centered between pad substring.
    • concat: Returns the concatenation of self with given other strings.
    • prepend: Returns the concatenation of a given other string with self.
    • ljust: Returns a copy of self of a given length, right-padded with a given other string.
    • rjust: Returns a copy of self of a given length, left-padded with a given other string.
  • Encoding:
    • b: Returns a copy of self with ASCII-8BIT encoding.
    • scrub: Returns a copy of self with each invalid byte replaced with a given character.
    • unicode_normalize: Returns a copy of self with each character Unicode-normalized.
    • encode: Returns a copy of self with all characters transcoded from one given encoding into another.
  • Substitution:
    • dump: Returns a copy of +self with all non-printing characters replaced by xHH notation and all special characters escaped.
    • undump: Returns a copy of +self with all \xNN notation replace by \uNNNN notation and all escaped characters unescaped.
    • sub: Returns a copy of self with the first substring matching a given pattern replaced with a given replacement string;.
    • gsub: Returns a copy of self with each substring that matches a given pattern replaced with a given replacement string.
    • succ, next: Returns the string that is the successor to self.
    • reverse: Returns a copy of self with its characters in reverse order.
    • tr: Returns a copy of self with specified characters replaced with specified replacement characters.
    • tr_s: Returns a copy of self with specified characters replaced with specified replacement characters, removing duplicates from the substrings that were modified.
    • %: Returns the string resulting from formatting a given object into self
  • Casing:
    • capitalize: Returns a copy of self with the first character upcased and all other characters downcased.
    • downcase: Returns a copy of self with all characters downcased.
    • upcase: Returns a copy of self with all characters upcased.
    • swapcase: Returns a copy of self with all upcase characters downcased and all downcase characters upcased.
  • Deletion:
    • delete: Returns a copy of self with characters removed
    • delete_prefix: Returns a copy of self with a given prefix removed.
    • delete_suffix: Returns a copy of self with a given suffix removed.
    • lstrip: Returns a copy of self with leading whitespace removed.
    • rstrip: Returns a copy of self with trailing whitespace removed.
    • strip: Returns a copy of self with leading and trailing whitespace removed.
    • chomp: Returns a copy of self with a trailing record separator removed, if found.
    • chop: Returns a copy of self with trailing whitespace or the last character removed.
    • squeeze: Returns a copy of self with contiguous duplicate characters removed.
    • [], slice: Returns a substring determined by a given index, start/length, or range, or string.
    • byteslice: Returns a substring determined by a given index, start/length, or range.
    • chr: Returns the first character.
  • Duplication:
    • to_s, $to_str: If self is a subclass of String, returns self copied into a String; otherwise, returns self.

Methods for Converting to Non-String:

Note

Each of these methods converts the contents of self to a non-String.:

  • Characters, Bytes, and Clusters:
    • bytes: Returns an array of the bytes in self.
    • chars: Returns an array of the characters in self.
    • codepoints: Returns an array of the integer ordinals in self.
    • getbyte: Returns an integer byte as determined by a given index.
    • grapheme_clusters: Returns an array of the grapheme clusters in self.
  • Splitting:
    • lines: Returns an array of the lines in self, as determined by a given record separator.
    • partition: Returns a 3-element array determined by the first substring that matches a given substring or regexp,
    • rpartition: Returns a 3-element array determined by the last substring that matches a given substring or regexp,
    • split: Returns an array of substrings determined by a given delimiter – regexp or string – or, if a block given, passes those substrings to the block.
  • Matching:
    • scan: Returns an array of substrings matching a given regexp or string, or, if a block given, passes each matching substring to the block.
    • unpack: Returns an array of substrings extracted from self according to a given format.
    • unpack1: Returns the first substring extracted from self according to a given format.
  • Numerics:
    • hex: Returns the integer value of the leading characters, interpreted as hexadecimal digits.
    • oct: Returns the integer value of the leading characters, interpreted as octal digits.
    • ord: Returns the integer ordinal of the first character in self.
    • to_i: Returns the integer value of leading characters, interpreted as an integer.
    • to_f: Returns the floating-point value of leading characters, interpreted as a floating-point number.
  • Strings and Symbols:
    • inspect: Returns copy of self, enclosed in double-quotes, with special characters escaped.
    • to_sym, intern: Returns the symbol corresponding to self.

Methods for Iterating:

  • each_byte: Calls the given block with each successive byte in self.
  • each_char: Calls the given block with each successive character in self.
  • each_codepoint: Calls the given block with each successive integer codepoint in self.
  • each_grapheme_cluster: Calls the given block with each successive grapheme cluster in self.
  • each_line: Calls the given block with each successive line in self, as determined by a given record separator.
  • upto: Calls the given block with each string value returned by successive calls to succ.

String manipulation#

Somes examples with string:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"%05d" % 123 # => "00123"

"Ho! " * 3                # => "Ho! Ho! Ho! "
"Hello from " + "foo" # => "Hello from foo"

'foo' <=> 'foo'  # => 0
'foo' <=> 'food' # => -1
'food' <=> 'foo' # => 1
'FOO' <=> 'foo'  # => -1
'foo' <=> 'FOO'  # => 1
'foo' <=> 1      # => nil

'foo' =~ /f/ # => 0
'foo' =~ /o/ # => 1
'foo' =~ /x/ # => nil

'bar'[2]    # => "r"
'bar'[-1]   # => "r"
'foo'[0, 2] # => "fo"
'foo'[/o/]  # => "o"

'hello World!'.capitalize # => "hello World!"
'Hello World!'.downcase   # => "hello world!"
'Hello World!'.upcase     # => "HELLO WORLD!"

"hello".chomp     #=> "hello"
"hello\n".chomp   #=> "hello"
"hello\r\n".chomp #=> "hello"

"hello".each_byte {|c| print c, ' ' } #=> 104 101 108 108 111

"hello".empty? # => false
" ".empty?     # => false
"".empty?      # => true

'foo'.include?('f')    # => true
'foo'.include?('fo')   # => true
'foo'.include?('food') # => false

"hello".length # => 5

" now's  the time ".split       #=> ["now's", "the", "time"]
" now's  the time ".split(' ')  #=> ["now's", "the", "time"]

"    hello    ".strip   #=> "hello"
"\tgoodbye\r\n".strip   #=> "goodbye"
"\x00\t\n\v\f\r ".strip #=> ""
"hello".strip           #=> "hello"

'hello'.sub(/[aeiou]/, '*')  # => "h*llo"

h = {'foo' => 'bar', 'baz' => 'bat'}
'food'.sub('foo', h) # => "bard"

Symbol#

Symbol Methods

Symbol objects represent named identifiers inside the Ruby interpreter. Most of time, symbols are used with config structure. Example:

1
2
3
4
config       = {:name => "Foo", :age  => 42}
other_syntax = {name: "Foo", age: 42}

config == other_syntax #=> true

Note

Symbol are managed by yaml, but not by json.

Integer#

Integer Methods

1
nb = 42

Integer Methods#

Comparing:

  • <: Returns whether self is less than the given value.
  • <=: Returns whether self is less than or equal to the given value.
  • <=>: Returns a number indicating whether self is less than, equal to, or greater than the given value.
  • == (aliased as ===): Returns whether self is equal to the given value.
  • >: Returns whether self is greater than the given value.
  • >=: Returns whether self is greater than or equal to the given value.

Converting:

  • ::sqrt: Returns the integer square root of the given value.
  • ::try_convert: Returns the given value converted to an Integer.
  • % (aliased as modulo): Returns self modulo the given value.
  • &: Returns the bitwise AND of self and the given value.
  • *: Returns the product of self and the given value.
  • **: Returns the value of self raised to the power of the given value.
  • +: Returns the sum of self and the given value.
  • -: Returns the difference of self and the given value.
  • /: Returns the quotient of self and the given value.
  • <<: Returns the value of self after a leftward bit-shift.
  • >>: Returns the value of self after a rightward bit-shift.
  • []: Returns a slice of bits from self.
  • ^: Returns the bitwise EXCLUSIVE OR of self and the given value.
  • ceil: Returns the smallest number greater than or equal to self.
  • chr: Returns a 1-character string containing the character represented by the value of self.
  • digits: Returns an array of integers representing the base-radix digits of self.
  • div: Returns the integer result of dividing self by the given value.
  • divmod: Returns a 2-element array containing the quotient and remainder results of dividing self by the given value.
  • fdiv: Returns the Float result of dividing self by the given value.
  • floor: Returns the greatest number smaller than or equal to self.
  • pow: Returns the modular exponentiation of self.
  • pred: Returns the integer predecessor of self.
  • remainder: Returns the remainder after dividing self by the given value.
  • round: Returns self rounded to the nearest value with the given precision.
  • succ (aliased as next): Returns the integer successor of self.
  • to_f: Returns self converted to a Float.
  • to_s (aliased as inspect): Returns a string containing the place-value representation of self in the given radix.
  • truncate: Returns self truncated to the given precision.
  • /: Returns the bitwise OR of self and the given value.

Other:

  • downto: Calls the given block with each integer value from self down to the given value.
  • times: Calls the given block self times with each integer in (0..self-1).
  • upto: Calls the given block with each integer value from self up to the given value.

Integer manipulation#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
10 % 2 # => 0
10 % 3 # => 1
10 % 4 # => 2

4 * 2  # => 8
4 * -2 # => -8

2 ** 3 # => 8

2 + 2  # => 4
-2 + 2 # => 0

4 - 2  # => 2
-4 - 2 # => -6

4 / 3  # => 1
4 / -3 # => -2

1 < 0 # => false
1 < 1 # => false
1 < 2 # => true

1 <= 0 # => false
1 <= 1 # => true

1 <=> 2 # => -1
1 <=> 1 # => 0
1 <=> 0 # => 1

1 > 0 # => true
1 > 1 # => false

1 >= 0 # => true
1 >= 1 # => true
1 >= 2 # => false

-12345.abs #=> 12345
12345.abs  #=> 12345

65.chr # => "A"

a = []
5.times {|i| a.push(i) } # => 5
a                        # => [0, 1, 2, 3, 4]

1.odd? #=> true
2.odd? #=> false

1.even? #=> false
2.even? #=> true

Float#

Float Methods

1
nb = 42.2

Float Methods#

Comparing:

  • <: Returns whether self is less than the given value.
  • <=: Returns whether self is less than or equal to the given value.
  • <=>: Returns a number indicating whether self is less than, equal to, or greater than the given value.
  • == (aliased as === and eql>): Returns whether self is equal to the given value.
  • >: Returns whether self is greater than the given value.
  • >=: Returns whether self is greater than or equal to the given value.

Converting:

  • % (aliased as modulo): Returns self modulo the given value.
  • *: Returns the product of self and the given value.
  • **: Returns the value of self raised to the power of the given value.
  • +: Returns the sum of self and the given value.
  • -: Returns the difference of self and the given value.
  • /: Returns the quotient of self and the given value.
  • ceil: Returns the smallest number greater than or equal to self.
  • coerce: Returns a 2-element array containing the given value converted to a Float and self
  • divmod: Returns a 2-element array containing the quotient and remainder results of dividing self by the given value.
  • fdiv: Returns the Float result of dividing self by the given value.
  • floor: Returns the greatest number smaller than or equal to self.
  • next_float: Returns the next-larger representable Float.
  • prev_float: Returns the next-smaller representable Float.
  • quo: Returns the quotient from dividing self by the given value.
  • round: Returns self rounded to the nearest value, to a given precision.
  • to_i (aliased as to_int): Returns self truncated to an Integer.
  • to_s (aliased as inspect): Returns a string containing the place-value representation of self in the given radix.
  • truncate: Returns self truncated to a given precision.

Float manipulation#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
-34.56.abs #=> 34.56
34.56.abs  #=> 34.56

f = 12345.6789
f.ceil(1) # => 12345.7
f.ceil(3) # => 12345.679

f = 12345.6789
f.floor(1) # => 12345.6
f.floor(3) # => 12345.678

f = 12345.6789
f.round(1) # => 12345.7
f.round(3) # => 12345.679

f = 2.0     # => 2.0
f.finite?   # => true
f = 1.0/0.0 # => Infinity
f.finite?   # => false

Array#

Array Methods

1
2
array = Array.new
array = []

Array Methods#

Methods for Querying:

  • length, size: Returns the count of elements.
  • include?: Returns whether any element == a given object.
  • empty?: Returns whether there are no elements.
  • all?: Returns whether all elements meet a given criterion.
  • any?: Returns whether any element meets a given criterion.
  • none?: Returns whether no element == a given object.
  • one?: Returns whether exactly one element == a given object.
  • count: Returns the count of elements that meet a given criterion.
  • find_index, index: Returns the index of the first element that meets a given criterion.
  • rindex: Returns the index of the last element that meets a given criterion.
  • hash: Returns the integer hash code.

Methods for Comparing:

  • #<=>: Returns -1, 0, or 1 as self is less than, equal to, or greater than a given object.
  • #==: Returns whether each element in self is == to the corresponding element in a given object.
  • eql?: Returns whether each element in self is eql? to the corresponding element in a given object.

Methods for Fetching:

Note

These methods do not modify self.

  • []: Returns one or more elements.
  • fetch: Returns the element at a given offset.
  • first: Returns one or more leading elements.
  • last: Returns one or more trailing elements.
  • max: Returns one or more maximum-valued elements, as determined by <=> or a given block.
  • max: Returns one or more minimum-valued elements, as determined by <=> or a given block.
  • minmax: Returns the minimum-valued and maximum-valued elements, as determined by <=> or a given block.
  • assoc: Returns the first element that is an array whose first element == a given object.
  • rassoc: Returns the first element that is an array whose second element == a given object.
  • at: Returns the element at a given offset.
  • values_at: Returns the elements at given offsets.
  • dig: Returns the object in nested objects that is specified by a given index and additional arguments.
  • drop: Returns trailing elements as determined by a given index.
  • take: Returns leading elements as determined by a given index.
  • drop_while: Returns trailing elements as determined by a given block.
  • take_while: Returns leading elements as determined by a given block.
  • slice: Returns consecutive elements as determined by a given argument.
  • sort: Returns all elements in an order determined by <=> or a given block.
  • reverse: Returns all elements in reverse order.
  • compact: Returns an array containing all non-nil elements.
  • select, filter: Returns an array containing elements selected by a given block.
  • uniq: Returns an array containing non-duplicate elements.
  • rotate: Returns all elements with some rotated from one end to the other.
  • bsearch: Returns an element selected via a binary search as determined by a given block.
  • bsearch_index: Returns the index of an element selected via a binary search as determined by a given block.
  • sample: Returns one or more random elements.
  • shuffle: Returns elements in a random order.

Methods for Assigning:

Note

These methods add, replace, or reorder elements in self.:

  • []=: Assigns specified elements with a given object.
  • push, append, <<: Appends trailing elements.
  • unshift, prepend: Prepends leading elements.
  • insert: Inserts given objects at a given offset; does not replace elements.
  • concat: Appends all elements from given arrays.
  • fill: Replaces specified elements with specified objects.
  • replace: Replaces the content of self with the content of a given array.
  • reverse!: Replaces self with its elements reversed.
  • rotate!: Replaces self with its elements rotated.
  • shuffle!: Replaces self with its elements in random order.
  • sort!: Replaces self with its elements sorted, as determined by <=> or a given block.
  • sort_by!: Replaces self with its elements sorted, as determined by a given block.

Methods for Deleting:

Note

Each of these methods removes elements from self.

  • pop: Removes and returns the last element.
  • shift: Removes and returns the first element.
  • compact!: Removes all non-nil elements.
  • delete: Removes elements equal to a given object.
  • delete_at: Removes the element at a given offset.
  • delete_if: Removes elements specified by a given block.
  • keep_if: Removes elements not specified by a given block.
  • reject!: Removes elements specified by a given block.
  • select!, filter!: Removes elements not specified by a given block.
  • slice!: Removes and returns a sequence of elements.
  • uniq!: Removes duplicates.

Methods for Combining:

  • #&: Returns an array containing elements found both in self and a given array.
  • intersection: Returns an array containing elements found both in self and in each given array.
  • +: Returns an array containing all elements of self followed by all elements of a given array.
  • -: Returns an array containiing all elements of self that are not found in a given array.
  • #|: Returns an array containing all elements of self and all elements of a given array, duplicates removed.
  • union: Returns an array containing all elements of self and all elements of given arrays, duplicates removed.
  • difference: Returns an array containing all elements of self that are not found in any of the given arrays..
  • product: Returns or yields all combinations of elements from self and given arrays.

Methods for Iterating:

  • each: Passes each element to a given block.
  • reverse_each: Passes each element, in reverse order, to a given block.
  • each_index: Passes each element index to a given block.
  • cycle: Calls a given block with each element, then does so again, for a specified number of times, or forever.
  • combination: Calls a given block with combinations of elements of self; a combination does not use the same element more than once.
  • permutation: Calls a given block with permutations of elements of self; a permutation does not use the same element more than once.
  • repeated_combination: Calls a given block with combinations of elements of self; a combination may use the same element more than once.
  • repeated_permutation: Calls a given block with permutations of elements of self; a permutation may use the same element more than once.

Methods for Converting:

  • map, collect: Returns an array containing the block return-value for each element.
  • map!, collect!: Replaces each element with a block return-value.
  • flatten: Returns an array that is a recursive flattening of self.
  • flatten!: Replaces each nested array in self with the elements from that array.
  • inspect, to_s: Returns a new String containing the elements.
  • join: Returns a newsString containing the elements joined by the field separator.
  • to_a: Returns self or a new array containing all elements.
  • to_ary: Returns self.
  • to_h: Returns a new hash formed from the elements.
  • transpose: Transposes self, which must be an array of arrays.
  • zip: Returns a new array of arrays containing self and given arrays; follow the link for details.

Other Methods:

  • *: Returns one of the following:
    • With integer argument n, a new array that is the concatenation of n copies of self.:
    • With string argument field_separator, a new string that is equivalent to join(field_separator).:
  • abbrev: Returns a hash of unambiguous abbreviations for elements.
  • pack: Packs the elements into a binary sequence.
  • sum: Returns a sum of elements according to either + or a given block.

Array manipulation#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
a = [0, 1] + [2, 3]

a = [:foo, 'bar', 2]
a << :baz # => [:foo, "bar", 2, :baz]

a = [:foo, 'bar', 2]
a[0] # => :foo
a[2] # => 2

a = [nil, 0, nil, 1, nil, 2, nil]
a.compact # => [0, 1, 2]

a = [:foo, 'bar', 2, 'bar']
a.delete('bar') # => "bar"
a # => [:foo, 2]

a = [:foo, 'bar', 2]
a.each {|element|  puts "#{element}" } # => "foo\nbar\n2\n"

a = [:foo, 'bar', 2]
a.each_index {|index|  puts "#{index} #{a[index]}" } # => "0 foo\n1 bar\n2 2\n"

a = []
a.empty? # => true
a << 'foo'
a.empty? # => false

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

[0, 1, 2].include?(2) # => true
[0, 1, 2].include?(3) # => false

[:foo, 'bar', 2].join # => "foobar2"
[:foo, 'bar', 2].join(', ') # => "foo, bar, 2"

a = [:foo, 'bar', 2]
a.last # => 2

a = [:foo, 'bar', 2]
a1 = a.map {|element| element.class }
a1 # => [Symbol, String, Integer]

a = [:foo, 'bar', 2]
a.pop # => 2
a # => [:foo, "bar"]

a = [:foo, 'bar', 2]
a.shift # => :foo
a # => ['bar', 2]

a = [:foo, 'bar', 2]
a.push(:baz, :bat) # => [:foo, "bar", 2, :baz, :bat]

a = [:foo, 'bar', 2]
a.insert(1, :bat, :bam) # => [:foo, :bat, :bam, "bar", 2]

a = [:foo, 'bar', 2, :bam]
a1 = a.select {|element| element.to_s.start_with?('b') }
a1 # => ["bar", :bam]

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

[1, 2, 3].size #=> 2

a = 'abcde'.split('').shuffle
a # => ["e", "b", "d", "a", "c"]
a1 = a.sort
a1 # => ["a", "b", "c", "d", "e"]

a = [0, 0, 1, 1, 2, 2]
a.uniq # => [0, 1, 2]

[1, 2, 3].inject(0, :+)       #=> 6
[1.0, 2, 3.3].inject(0.0, :+) #=> 6.3

Hash#

Hash Methods

1
2
3
4
5
6
7
8
foo  = {}
bar  = Hash.new
hash = Hash.new { |hash, key| hash[key] = 3 }

foo[:total] += 39 # => undefined method `+' for nil:NilClass (NoMethodError)
foo[:total] = 42  # => 42

hash[:total] += 39 # => 42

Hash Methods#

Methods for Querying:

  • any?: Returns whether any element satisfies a given criterion.
  • compare_by_identity?: Returns whether the hash considers only identity when comparing keys.
  • default: Returns the default value, or the default value for a given key.
  • default_proc: Returns the default proc.
  • empty?: Returns whether there are no entries.
  • eql?: Returns whether a given object is equal to self.
  • hash: Returns the integer hash code.
  • has_value?: Returns whether a given object is a value in self.
  • include?, has_key?, member?, key?: Returns whether a given object is a key in self.
  • length, size: Returns the count of entries.
  • value?: Returns whether a given object is a value in self.

Methods for Comparing:

  • #<: Returns whether self is a proper subset of a given object.
  • #<=: Returns whether self is a subset of a given object.
  • #==: Returns whether a given object is equal to self.
  • #>: Returns whether self is a proper superset of a given object
  • #>=: Returns whether self is a proper superset of a given object.

Methods for Fetching:

  • []: Returns the value associated with a given key.
  • assoc: Returns a 2-element array containing a given key and its value.
  • dig: Returns the object in nested objects that is specified by a given key and additional arguments.
  • fetch: Returns the value for a given key.
  • fetch_values: Returns array containing the values associated with given keys.
  • key: Returns the key for the first-found entry with a given value.
  • keys: Returns an array containing all keys in self.
  • rassoc: Returns a 2-element array consisting of the key and value of the first-found entry having a given value.
  • values: Returns an array containing all values in self/
  • values_at: Returns an array containing values for given keys.

Methods for Assigning:

  • []=, store: Associates a given key with a given value.
  • merge: Returns the hash formed by merging each given hash into a copy of self.
  • merge!, update: Merges each given hash into self.
  • replace: Replaces the entire contents of self with the contents of a givan hash.

Methods for Deleting:

  • These methods remove entries from self:
    • clear: Removes all entries from self.
    • compact!: Removes all nil-valued entries from self.
    • delete: Removes the entry for a given key.
    • delete_if: Removes entries selected by a given block.
    • filter!, select!: Keep only those entries selected by a given block.
    • keep_if: Keep only those entries selected by a given block.
    • reject!: Removes entries selected by a given block.
    • shift: Removes and returns the first entry.
  • These methods return a copy of self with some entries removed:
    • compact: Returns a copy of self with all nil-valued entries removed.
    • except: Returns a copy of self with entries removed for specified keys.
    • filter, select: Returns a copy of self with only those entries selected by a given block.
    • reject: Returns a copy of self with entries removed as specified by a given block.
    • slice: Returns a hash containing the entries for given keys.

Methods for Iterating:

  • each, each_pair: Calls a given block with each key-value pair.
  • each_key: Calls a given block with each key.
  • each_value: Calls a given block with each value.

Methods for Converting:

  • inspect, to_s: Returns a new String containing the hash entries.
  • to_a: Returns a new array of 2-element arrays; each nested array contains a key-value pair from self.
  • to_h: Returns self if a Hash; if a subclass of Hash, returns a Hash containing the entries from self.
  • to_hash: Returns self.
  • to_proc: Returns a proc that maps a given key to its value.

Methods for Transforming Keys and Values:

  • transform_keys: Returns a copy of self with modified keys.
  • transform_keys!: Modifies keys in self
  • transform_values: Returns a copy of self with modified values.
  • transform_values!: Modifies values in self.

Other Methods:

  • flatten: Returns an array that is a 1-dimensional flattening of self.
  • invert: Returns a hash with the each key-value pair inverted.

Hash manipulation#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
h = {foo: 0, bar: 1, baz: 2}
h[:foo] # => 0

h = {foo: 0, bar: nil, baz: 2, bat: nil}
h1 = h.compact
h1 # => {:foo=>0, :baz=>2}

h = {foo: 0, bar: 1, baz: 2}
h.delete(:bar) # => 1
h # => {:foo=>0, :baz=>2}

h = {foo: 0, bar: 1, baz: 2}
h.delete_if {|key, value| value > 0 } # => {:foo=>0}

h = {foo: 0, bar: 1, baz: 2}
h.each_pair {|key, value| puts "#{key}: #{value}"} # => "foo: 0\nbar: 1\nbaz: 2"

h = {foo: 0, bar: 1, baz: 2}
h.each_key {|key| puts key }  # => "foo\nbar\nbaz"

h = {foo: 0, bar: 1, baz: 2}
h.each_value {|value| puts value } # => "0\n1\n2"

{}.empty? # => true
{foo: 0, bar: 1, baz: 2}.empty? # => false

h = {foo: 0, bar: 1, baz: 2}
h.keys # => [:foo, :bar, :baz]

h = {foo: 0, bar: 1, baz: 2}
h.key?(:foo)  # => true
h.key?(:lala) # => false

h = {foo: 0, bar: 1, baz: 2}
h1 = {bat: 3, bar: 4}
h2 = {bam: 5, bat:6}
h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}

{foo: 0, bar: 1, baz: 2}.length # => 3
{foo: 0, bar: 1, baz: 2}.size   # => 3

h = {foo: 0, bar: 1, baz: 2}
h.select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}

h = {foo: 0, bar: 1, baz: 2}
h.values # => [0, 1, 2]

h = {foo: 0, bar: 1, baz: 2}
h.value?(1) # => true
h.value?(4) # => false