intro
- key-value pairs
merge method
- merge is used for merging hashes together.
- it's for hash only, not for array and ranges.
- basic merge: h1.merge(h2) # default with new value.
- h1.merge(h2) {|k, o, n| o} # use origin hash value.
- h1.merge(h2) {|k, o, n| n} # use new hash value.
- h1.merge(h2) {|k, o, n| o + n} # use sum of two.
- h1.merge(h2) {|k, o, n| o > n ? o : n} # use the max one.
map, collect
- when to use it? when you feel lazy, manipulate all elements.
- %w(apple banana orange).map {|fruit| fruit.capitalize if fruit.start_with?('b') }
- return => [nil, "Banana", nil]
- tip1: need a return value for each iteration, otherwise it will be nil
- tip2: the number of items in equals the number of items out.
- tip3: even though it works with array, hash, and range, it always return array.
reduce, inject
- an accumulator that accumulates values in memo.
- (1..10).reduce {|memo, n| memo + n} same as (1..10).reduce(&:+)
- tip: need a return value as memo in each iteration.
sort
- provide a comparison operator (space ship operator) <=> to compare.
- comparison operator is going to do more than just check true or false.
- a <=> b, return -1 if a less than b, 1 if a greater than b, 0 if a equal to b.
- e.g. normal sort: (1..10).sort
- e.g. reverse sort: (1..10).sort {|a, b| b <=> a}
- e.g. %w(apple banana pear).sort_by(&:length)
- sort is support for array, range and hashes.
- when sort hash, ruby convert it to array first:
- hash = {c: 3, a: 5, b: 4, d: 2, e: 1}
- hash.sort {|a, b| a[0] <=> b[0]}
- hash.sort {|a, b| a[1] <=> b[1]}