Array Flashcards

1
Q

.each_with_index

A

Answer:
def accum(s)
s.chars.each_with_index.map{ |c, i| c.upcase + c.downcase * i }.join(‘-‘)
end

My answer:
def accum(s)
   out = []
   i = 1
   s.chars.each do |letter|
     out << (letter*i).capitalize
     i = i + 1
  end
  out.join('-')
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

.minmax

A
def high_and_low(numbers)
  numbers.split.map(&amp;:to_i).minmax.reverse.join(' ')
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

.tr

A

def DNA_strand(dna)
dna.tr(“ACTG”, “TGAC”)
end

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

descending_order

Input: 145263 Output: 654321

A
def descending_order(n)
  n.to_s.chars.map(&amp;:to_i).sort.reverse.join.to_i
end

n.digits.sort.reverse.join.to_i

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

.sort

A

sort → new_aryclick to toggle source
sort { |a, b| block } → new_ary
Returns a new array created by sorting self.

Comparisons for the sort will be done using the <=> operator or using an optional code block.

The block must implement a comparison between a and b and return an integer less than 0 when b follows a, 0 when a and b are equivalent, or an integer greater than 0 when a follows b.

The result is not guaranteed to be stable. When the comparison of two elements returns 0, the order of the elements is unpredictable.

a = [ “d”, “a”, “e”, “c”, “b” ]

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

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

.is_a?

A

> 1.is_a? Integer
=> true

is_a? matches on an exact class name, while kind_of? will match the given class and any sub-classes. Because of this, I tend to use kind_of? almost exclusively. This lets me use a child class in place of its parent class without breaking the test.

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