ruby using the “&:methodname” shortcut from array.map(&:methodname) for hash key strings rather than methodname

后端 未结 2 1223
一生所求
一生所求 2020-12-09 08:35

Most ruby developers know how to save a few keystrokes by doing something like this:

array.map(&:methodname)

rather than



        
2条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 09:00

    You can do this with a lambda:

    extract_keyname = ->(h) { h[:keyname] }
    ary_of_hashes.map(&extract_keyname)
    

    This tends to be more useful if the block's logic is more complicated than simply extracting a value from a Hash. Also, attaching names to your bits of logic can help clarify what a chain of Enumerable method calls is trying to do.

    You can also have a lambda which returns a lambda if you're doing this multiple times:

    extract = ->(k) { ->(h) { h[k] } }
    ary_of_hashes.map(&extract[:keyname])
    ary_of_hashes.map(&extract[:other_key])
    

    or a lambda building method:

    def extract(k)
      ->(h) { h[k] }
    end
    
    ary_of_hashes.map(&extract(:keyname))
    ary_of_hashes.map(&extract(:other_key))
    

提交回复
热议问题