methods Flashcards
.tap
A debugging tool. Object instance method.
tap {|x| block } → obj
Yields self to the block, and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.
It simply passes the calling object into a block, then returns that object.
.take
arr = [1, 2, 3, 4, 5]
arr.take(2)
=> [1, 2]
it’s non destructive
=> [1, 2, 3, 4, 5]
.between?
between?(min, max) → true or false
Returns false if obj <=> min is less than zero or if obj <=> max is greater than zero, true otherwise.
examples:
3.between?(1, 5) #=> true
6.between?(1, 5) #=> false
‘cat’.between?(‘ant’, ‘dog’) #=> true
‘gnu’.between?(‘ant’, ‘dog’) #=> false
example:
loop do
number = rand(100)
puts number
if number.between?(0, 10)
break
end
end
.each_pair
Hash#each_pair.
Calls the given block with each key-value pair; returns self:
example:
h = {foo: 0, bar: 1, baz: 2}
h.each_pair { |key, value| puts “#{key}: #{value}” } # => {:foo=>0, :bar=>1, :baz=>2}
example:
munsters.each_pair do |name, details|
puts “#{name} is a #{details[‘age’]} year old #{details[‘gender’]}”
end
.ord
You can determine a string’s ASCII position by calling ord on the string.
examples:
‘b’.ord # => 98
‘}’.ord # => 125
.sub
.gsub!
greeting = ‘Hello!’
greeting.gsub!(‘Hello’, ‘Goodbye’)
puts greeting
.reduce or .inject
combines all elements by applying a binary operation, specified by a block or a symbol that names a method or operator.
# Sum some numbers (5..10).reduce(:+) #=> 45 # Same using a block and inject (5..10).inject { |sum, n| sum + n } #=> 45
.count
returns a count of specified elements.
count → an_integer
count(obj) → an_integer
count {|element| … } → an_integer
Returns a count of specified elements.
With no argument and no block, returns the count of all elements:
[0, 1, 2].count # => 3
[].count # => 0
With argument obj, returns the count of elements == to obj:
[0, 1, 2, 0.0].count(0) # => 2
[0, 1, 2].count(3) # => 0
With no argument and a block given, calls the block with each element; returns the count of elements for which the block returns a truthy value:
[0, 1, 2, 3].count {|element| element > 1} # => 2
.sum
For example, [e1, e2, e3].sum returns init + e1 + e2 + e3.
Examples:
a = [0, 1, 2, 3]
a. sum # => 6
a. sum(100) # => 106
.chop
Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.
"string\r\n".chop #=> "string" "string\n\r".chop #=> "string\n" "string\n".chop #=> "string" "string".chop #=> "strin" "x".chop.chop #=> ""
.delete
String#delete
string that starts with ^ is negated.
examples: "hello".delete "l","lo" #=> "heo" "hello".delete "lo" #=> "he" "hello".delete "aeiou", "^e" #=> "hell" "hello".delete "ej-m" #=> "ho"
.sum
sum(init = 0) → object sum(init = 0) {|element| ... } → object
When no block is given, returns the object equivalent to:
sum = init
array.each {|element| sum += element }
sum
For example, [e1, e2, e3].sum returns init + e1 + e2 + e3.
Examples:
a = [0, 1, 2, 3]
a. sum # => 6
a. sum(100) # => 106
The elements need not be numeric, but must be +-compatible with each other and with init:
a = [‘abc’, ‘def’, ‘ghi’]
a.sum(‘jkl’) # => “jklabcdefghi”
.nil?
responds true or false
examples:
nil_variable = nil
age = 26
nil_variable.nil? # true
age.nil? # false
.upto or .downto
examples: 95.upto(100) { |num| print num, " " } # Prints 95 96 97 98 99 100
“L”.upto(“P”) { |letter| puts letter }
.respond_to?( )
.respond_to? takes a symbol and returns true if an object can receive that method and false otherwise. For example,
[1, 2, 3].respond_to?(:push)
would return true, since you can call .push on an array object. However,
[1, 2, 3].respond_to?(:to_sym)
would return false, since you can’t turn an array into a symbol.
.divmod( )
The #divmod method computes both the integer result of the division and its modulo value.
16.divmod(5)
=> [3, 1]
p
p outputs argument then returns argument, unlike puts or prints which returns nil.
.select
on hash or array passes a block
hash:
select {|key, value| … } → new_hash
select → new_enumerator
Returns a new Hash object whose entries are those for which the block returns a truthy value:
name_and_age.select { |k,v| k == “Bob” }
=> {“Bob”=>42}
name_and_age.select { |k,v| (k == “Bob”) || (v == 19) }
=> {“Bob”=>42, “Joe”=>19}
h = {foo: 0, bar: 1, baz: 2}
h. select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
- ———–
array:
select {|element| … } → new_array
select → new_enumerator
Calls the block, if given, with each element of self; returns a new Array containing those elements of self for which the block returns a truthy value:
a = [:foo, ‘bar’, 2, :bam]
a1 = a.select {|element| element.to_s.start_with?(‘b’) }
a1 # => [“bar”, :bam]