Wednesday, 15 February 2012

ruby - Replace elements in an array whose indexes do not match the given indexes -



ruby - Replace elements in an array whose indexes do not match the given indexes -

i have next 2 variables:

array = ['h','e','l','l','o'] string = '023'

all elements in array not have indexes matching someplace in string need replaced underscores. new array should this: ['h','_','l','l','_'].

i thinking of doing this

.map.with_index |e,i| if (i != string) #somehow check entire string e = '_' end end

array = ['h','e','l','l','o'] string = '023'

surely, first step convert string array of indices, way should stored in first place, in part allow utilize of indices greater nine:

indices = string.each_char.map(&:to_i) #=> [0, 2, 3]

once done, there umpteen ways replacements. assuming array not mutated, here's straightforward way:

indices.each_with_object([?_]*array.size) { |i,arr| arr[i] = array[i] } #=> ["h", "_", "l", "l", "_"]

if prefer, these 2 lines combined:

string.each_char.map(&:to_i).each_with_object([?_]*array.size) |i,arr| arr[i] = array[i] end

alternatively,

string.each_char.with_object([?_]*array.size) |c,arr| = c.to_i arr[i] = array[i] end

ruby arrays indexing

No comments:

Post a Comment