enumerable - How to implement slice_after (or group certain elements with certain subsequent ones) in Ruby? -
the enumerable#slice_before method quite useful, , says on tin - slice array before element if condition on element met. example, using group numbers following ones.
in case, ids 0xf0 0xfb should grouped ids come after them, including multiple of these ids in row (they "modifier" flags in thing i'm making). i'm doing this:
# example code (for sscce) code = '00ff1234f0aaf0bbf0ccccf3f4f5aaaaaa'.split('').each_slice(2).map{|n| n.join.to_i 16 } # grouping modifiers (more may added later, array used) code = code.slice_before {|tkn| ![*0xf0..0xfb].include? tkn }.to_a the result of code after is
[[0], [255], [18], [52, 240], [170, 240], [187, 240], [204], [204, 243, 244, 245], [170], [170], [170]] however, desired result is
[[0], [255], [18], [52], [240, 170], [240, 187], [240, 204], [204], [243, 244, 245, 170], [170], [170]] i found this entry on bugs.ruby-lang.org, , response was
the main reason [that not implemented] no 1 requested.
i have not enough time implement now.
therefore, how can implement myself?
it's not elegant one-liner i'd have, gets job done :)
target = [] code.each |i| # if there previous element , 1 of "modifiers" if target.last && [*0xf0..0xfb].include?(target.last.last) # append current subarray target.last << else # otherwise, append new subarray target << [i] end end you'll find desired array in target code being unchanged.
Comments
Post a Comment