Array Flashcards
.each_with_index
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
.minmax
def high_and_low(numbers) numbers.split.map(&:to_i).minmax.reverse.join(' ') end
.tr
def DNA_strand(dna)
dna.tr(“ACTG”, “TGAC”)
end
descending_order
Input: 145263 Output: 654321
def descending_order(n) n.to_s.chars.map(&:to_i).sort.reverse.join.to_i end
n.digits.sort.reverse.join.to_i
.sort
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”]
.is_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.