How to remove only a single instance of a value from an array in Ruby? -


the removal methods removing given value array seem remove every instance of supplied value. without knowing position, how remove single instance?

foo = 4,4,3,2,6 foo -= [4] p foo # --> [3, 2, 6] 

i same result foo.delete(4)

i can query array discern if instance of value exists within , count number of instances:

foo = 4,4,3,2,6 foo.include?(4) # <-- true foo.count(4)    # <-- 2 

if, example, array of dice rolls made game of yahtzee:

roll_1 = array.new(5) {rand(1..6)} 

and resulting values [4, 4, 3, 2, 6] player might want select either both fours, or, 2, 3, & 4 straight. in case player wants hold on single 4 straight, how can choose single instance of value in way value verified being in array?

you can use #index (or #find_index) find index of first matching element, , #delete_at (or #slice!) delete element:

foo.delete_at(foo.index(4)) 

here's thread discusses issue. recommend adding guard in case value being searched doesn't appear in array:

foo.delete_at(foo.index(4) || foo.length) 

you use flag variable , #delete_if until flag flipped:

flag = false foo.delete_if { |i| break if flag; !flag , == 4 , flag = true } 

you partition array matches , non-matches, remove 1 of matches, , reconcatenate array:

matches, foo = foo.partition { |i| == 4 } foo.concat(matches[0..-2]) 

but think first option best. :-)


Comments