Enumerators Flashcards
return a new array with each value multiplied by two:
arr = [ 1, 2, 3, 4 ]
arr = [ 1, 2, 3, 4 ] newArray = arr.map { |x| x * 2 }
what is a another name for the MAP method?
COLLECT
Return the sum of all values in the given array:
nums = [1, 2, 3, 4, 5]
nums = [1, 2, 3, 4, 5]
nums.inject(0) do |accum, element| # accum is initially set to 0, the method argument
accum + element
end
what is another name for the INJECT method?
REDUCE
Return the items from the given range that are divisible by 3:
num = ( 1..10 )
nums = ( 1..10 ) nums.select do | i | i % 3 == 0 end # ==> [3, 6, 9 ]
What is another name for the SELECT method?
FIND_ALL
nums = [1, 4, 5, 6, 7 ]
nums.count # ==> 5
Does this array contain a 4?
nums = [ 1, 4, 5, 6, 7 ]
nums.include?(4)
Does the array contain even numbers?
nums = [2, 3, 5, 7 ]
nums.any? do |x|
x % 2 == 0
end
What methods would you use to determine if all or none of the collection equal a value or criteria?
ALL? / NONE?
Write a method that finds the median of a given array of integers. If the array has an odd number of integers, return the middle item from the sorted array. If the array has an even number of integers, return the average of the middle two items from the sorted array.
…
Create a method that takes in an Array of Strings and uses inject to return the concatenation of the strings.
..
How would you write a block given an array of positive integers and return another array with only the values over 100?
arr.select do |x|
x >= 100
end