methods Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

.tap

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

.take

arr = [1, 2, 3, 4, 5]
arr.take(2)

A

=> [1, 2]
it’s non destructive
=> [1, 2, 3, 4, 5]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

.between?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

.each_pair

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

.ord

A

You can determine a string’s ASCII position by calling ord on the string.

examples:
‘b’.ord # => 98
‘}’.ord # => 125

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

.sub

.gsub!

A

greeting = ‘Hello!’

greeting.gsub!(‘Hello’, ‘Goodbye’)
puts greeting

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

.reduce or .inject

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

.count

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

.sum

A

For example, [e1, e2, e3].sum returns init + e1 + e2 + e3.

Examples:

a = [0, 1, 2, 3]

a. sum # => 6
a. sum(100) # => 106

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

.chop

A

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       #=> ""
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

.delete

A

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"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

.sum

A
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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

.nil?

A

responds true or false

examples:
nil_variable = nil
age = 26

nil_variable.nil? # true
age.nil? # false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

.upto or .downto

A
examples:
95.upto(100) { |num| print num, " " }
# Prints 95 96 97 98 99 100

“L”.upto(“P”) { |letter| puts letter }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

.respond_to?( )

A

.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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

.divmod( )

A

The #divmod method computes both the integer result of the division and its modulo value.

16.divmod(5)
=> [3, 1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

p

A

p outputs argument then returns argument, unlike puts or prints which returns nil.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

.select

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

has_key?

A

returns boolean for a hash

20
Q

fetch

A

The fetch method allows you to pass a given key and it will return the value for that key if it exists. You can also specify an option for return if that key is not present.

name_and_age.fetch(“Steve”)
=> 31

name_and_age.fetch("Larry")
=> KeyError: key not found: "Larry"
     from (irb):32:in `fetch'
     from (irb):32
     from /usr/local/rvm/rubies/ruby-2.5.3/bin/irb:16:in `'

name_and_age.fetch(“Larry”, “Larry isn’t in this hash”)
=> “Larry isn’t in this hash”

21
Q

to_a

A

The to_a method returns an array version of your hash when called. Let’s see it in action. It doesn’t modify the hash permanently though.

name_and_age.to_a
=> [[“Bob”, 42], [“Steve”, 31], [“Joe”, 19]]

name_and_age
=> {“Bob”=>42, “Steve”=>31, “Joe”=>19}

22
Q

keys

values

A

returns an array

name_and_age.keys
=> [“Bob”, “Steve”, “Joe”]
name_and_age.values
=> [42, 31, 19]

Notice that the returned values are in array format. Because it’s returning an array, you can do interesting things like printing out all the keys in a hash: name_and_age.keys.each { |k| puts k }.

23
Q

.each_key

A

calls the given block with each key, returns self

opposites.each_key { |key| puts key }

24
Q

.each_value

A

calls the given block with each value,
returns self

opposites.each_value { |value| puts value }

25
Q

.sqrt

A

calculate the square root of a number.

Math.sqrt(400)
=> 20.0

26
Q

Time

A
Time class
What if you wanted to calculate what specific day July 4th occurred in 2008? You can use Ruby's built-in Time class.

t = Time.new(2008, 7, 4)
=> 2008-07-04 00:00:00 -0400

t.monday?
=> false

t.friday?
=> true

27
Q

start_with?

A

method

28
Q

.times

A

times {|i| block } → self
times → an_enumerator

Iterates the given block int times, passing in values from zero to int - 1.

If no block is given, an Enumerator is returned instead.

5.times {|i| print i, “ “ } #=> 0 1 2 3 4

29
Q

.cover

A

(10..100).cover?(42)

30
Q

.assoc

A

Given the hash below:

flintstones = { “Fred” => 0, “Wilma” => 1, “Barney” => 2, “Betty” => 3, “BamBam” => 4, “Pebbles” => 5 }

Turn this into an array containing only two elements: Barney’s name and Barney’s number

flintstones.assoc(“Barney”)

31
Q

.empty?

A

empty? is a method that can be used on strings, arrays, hashes and sets. It returns true if the instance of the object has a length of zero.

When used on strings, it returns true for empty strings.

”“.empty?
=> true

Note that whitespace characters are characters and so using #empty? on a string containing only whitespace will return false.

Because of this, it might not be the best method to use when validating text. If you are only using this method to validate user input, for instance, you might end up processing input that only contains whitespace.

” “.empty?
=> false

32
Q

.sample

A

computer chooses

33
Q

.swapcase

A

Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.

examples:
“Hello”.swapcase #=> “hELLO”
“cYbEr_PuNk11”.swapcase #=> “CyBeR_pUnK11”

34
Q

match?( )

A

Returns true or false based on whether a match is found for self and pattern.
regexp = Regexp.new(pattern)

Returns true if self+.match(regexp) returns a Matchdata object, false otherwise:

‘foo’.match?(/o/) # => true
‘foo’.match?(‘o’) # => true
‘foo’.match?(/x/) # => false

If Integer argument offset is given, the search begins at index offset:

‘foo’.match?(‘f’, 1) # => false
‘foo’.match?(‘o’, 1) # => true

35
Q

.center

A

Centers str in width. If width is greater than the length of str, returns a new String of length width with str centered and padded with padstr; otherwise, returns str.

“hello”.center(4) #=> “hello”
“hello”.center(20) #=> “ hello “
“hello”.center(20, ‘123’) #=> “1231231hello12312312”

example:
title = “Flintstone Family Members”
title.center(40)

36
Q

.include?

A

include?(key) → true or false

Methods has_key?, key?, and member? are aliases for #include?.

Returns true if key is a key in self, otherwise false.

example:
ages = { “Herman” => 32, “Lily” => 30, “Grandpa” => 402, “Eddie” => 10 }

ages.include?(“Spot”)
=> false

37
Q

.prepend

A

example:
put the expected “Four score and “ in front of
famous_words = “seven years ago…”

famous_words.prepend(“Four score and “)

38
Q

.assoc

A

Given the hash below

flintstones = { “Fred” => 0, “Wilma” => 1, “Barney” => 2, “Betty” => 3, “BamBam” => 4, “Pebbles” => 5 }

Turn this into an array containing only two elements: Barney’s name and Barney’s number

flintstones.assoc("Barney")
#=> ["Barney", 2]
39
Q

.slice

A

Returns elements from self; does not modify self.

When a single Integer argument index is given, returns the element at offset index:

a = [:foo, ‘bar’, 2]
a[0] # => :foo
a[2] # => 2
a # => [:foo, “bar”, 2]

If index is negative, counts relative to the end of self:

a = [:foo, ‘bar’, 2]
a[-1] # => 2
a[-2] # => “bar”

If index is out of range, returns nil.

When two Integer arguments start and length are given, returns a new Array of size length containing successive elements beginning at offset start:

a = [:foo, ‘bar’, 2]
a[0, 2] # => [:foo, “bar”]
a[1, 2] # => [“bar”, 2]

If start + length is greater than self.length, returns all elements from offset start to the end:

a = [:foo, ‘bar’, 2]
a[0, 4] # => [:foo, “bar”, 2]
a[1, 3] # => [“bar”, 2]
a[2, 2] # => [2]

If start == self.size and length >= 0, returns a new empty Array.

If length is negative, returns nil.

When a single Range argument range is given, treats range.min as start above and range.size as length above:

a = [:foo, ‘bar’, 2]
a[0..1] # => [:foo, “bar”]
a[1..2] # => [“bar”, 2]

Special case: If range.start == a.size, returns a new empty Array.

If range.end is negative, calculates the end index from the end:

a = [:foo, ‘bar’, 2]
a[0..-1] # => [:foo, “bar”, 2]
a[0..-2] # => [:foo, “bar”]
a[0..-3] # => [:foo]

If range.start is negative, calculates the start index from the end:

a = [:foo, ‘bar’, 2]
a[-1..2] # => [2]
a[-2..2] # => [“bar”, 2]
a[-3..2] # => [:foo, “bar”, 2]

If range.start is larger than the array size, returns nil.

a = [:foo, ‘bar’, 2]
a[4..1] # => nil
a[4..0] # => nil

example:
str = ‘abcdefghi’
str[2, 3] # => “cde”

40
Q

.inject or .reduce

A
# Sum some numbers
(5..10).reduce(:+)                             #=> 45
# Same using a block and inject
(5..10).inject { |sum, n| sum + n }            #=> 45
# Multiply some numbers
(5..10).reduce(1, :*)                          #=> 151200
# Same using a block
(5..10).inject(1) { |product, n| product * n } #=> 151200
41
Q

.squeeze

A

takes a string. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.

“yellow moon”.squeeze #=> “yelow mon”
“ now is the”.squeeze(“ “) #=> “ now is the”
“putters shoot balls”.squeeze(“m-z”) #=> “puters shot balls”

42
Q

.center

A

Centers str in width. If width is greater than the length of str, returns a new String of length width with str centered and padded with padstr; otherwise, returns str.

“hello”.center(4) #=> “hello”
“hello”.center(20) #=> “ hello “
“hello”.center(20, ‘123’) #=> “1231231hello12312312”

43
Q

.find

A
def find_dup(array)
  array.find { |element| array.count(element) == 2 }
end

Here we’re using the method Enumerable#find to look through each item in our array. If that item meets some condition we return it. In this case, the condition we check is that that item occurs twice. This bit of code will allow us to find the duplicate element regardless of the size of the array.

Returns the first element for which the block returns a truthy value.

With a block given, calls the block with successive elements of the collection; returns the first element for which the block returns a truthy value:

(0..9).find {|element| element > 2} # => 3

{foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?(‘b’) } # => [:bar, 1]

44
Q

.zip

A
Array#zip
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2, :b3]
c = [:c0, :c1, :c2, :c3]
d = a.zip(b, c)
d # => [[:a0, :b0, :c0], [:a1, :b1, :c1], [:a2, :b2, :c2], [:a3, :b3, :c3]]

more examples and uses in documentation.

45
Q

Kernel#format

A

https://medium.com/@kristenfletcherwilde/getting-started-with-kernel-format-7c7645266fed

46
Q

.rotate

A

a = [:foo, ‘bar’, 2, ‘bar’]
a1 = a.rotate
a1 # => [“bar”, 2, “bar”, :foo]

a = [:foo, ‘bar’, 2]
a1 = a.rotate(2)
a1 # => [2, :foo, “bar”]

when it’s a negative number, rotates in the opposite direction, from end to beginning:
a = [:foo, ‘bar’, 2]
a1 = a.rotate(-2)
a1 # => [“bar”, 2, :foo]

47
Q

keep_if

A

array, hash

h = {foo: 0, bar: 1, baz: 2}

h.keep_if { |key, value| key.start_with?(‘b’) }

=> {:bar=>1, :baz=>2}