ruby create sub arrays if element includes same letter -
i have array this:
["b3", "a3", "a5", "b2"]
and need this:
[["b3", "b2"] ["a3", "a5"]]
i have tried various things including:
["b3", "a3", "a5", "b2"].map { |i| i.include? 'a' } # => returns [false, true, true, false] ["b3", "a3", "a5", "b2"].detect { |i| i.include? 'a' } # returns "a3"
is there simple way done?
thanks
a = ["b3", "a3", "a5", "b2"] a.group_by { |s| s[0] }.values #=> [["b3", "b2"], ["a3", "a5"]]
enumerable#group_by produces:
h = a.group_by { |s| s[0] } #=> {"b"=>["b3", "b2"], "a"=>["a3", "a5"]}
and use hash#values extract values:
h.values #=> [["b3", "b2"], ["a3", "a5"]]
Comments
Post a Comment