Ruby: Hash

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]}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容