{|_, e| e.length>1} what is the use of underScore ( _ ) in Ruby?

后端 未结 2 1985
小蘑菇
小蘑菇 2021-01-24 04:40
country =
  [\"UK\", \"US\", \"RS\", \"EU\", \"UK\", \"US\"].
    group_by{ |e| e }.
    keep_if{ |_, e | e.length > 1 }
#⇒ {\"UK\"=>[\"UK\", \"UK\"], \"US\"=>[         


        
2条回答
  •  -上瘾入骨i
    2021-01-24 05:30

    By convention, underscore is used as a variable name for a value that is not used. Unlike other variable names, it can be used multiple times in a single parallel assignment.

    In this particular case, the filter in the block is not interested in the key of the hash, but only the value of the hash, which is an array generated by group_by.

提交回复
热议问题