2014-11-06 244 views
1

我有以下两个变量:替换元素

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

所有在array元素没有索引的string匹配某个地方需要被替换下划线。新阵列应该如下所示:['h','_','l','l','_']

我想这样做这样

.map.with_index do |e,i| 
    if (i != string) #Somehow get it to check the entire string 
    e = '_' 
    end 
end 
+1

你的问题是什么? – sawa 2014-11-06 18:40:07

+2

“023”扩展为“[0,2,3]”还是“[0,23]”?这个问题会得到改善,你可以将它改变为一系列索引。 – 2014-11-06 19:08:08

回答

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

当然,第一步是string转换为指数的阵列,他们可能应存放在首位的方式,在部分允许使用大于九的指数:

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

一旦完成,有很多方法可以进行替换。假设array不被突变,这里是一个非常简单的方法:

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

如果你愿意的话,这两条线可以合并:

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

另外,

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

我真的很喜欢'indices.each_with_object([?_] * array.size){| i,arr | arr [i] = array [i]}行。荣誉。 – Surya 2014-11-06 19:54:14

2

东西既然你已经知道了位置保留的,只是把它作为一种模式:

array = %w[ h e l l o ] 
string = '023' 

# Create a replacement array that's all underscores 
replacement = [ '_' ] * array.length 

# Transpose each of the positions that should be preserved 
string.split(//).each do |index| 
    index = index.to_i 

    replacement[index] = array[index] 
end 

replacement 
# => ["h", "_", "l", "l", "_"] 

如果你的索引说明的变化,你”我们需要重新编写解析器来进行相应的转换。例如,如果您需要9位以上的数字,则可以切换为逗号分隔。

+0

恕我直言,你应该使用'each_char'而不是'split(//)。' – ThomasSevestre 2014-11-06 18:54:05

+0

我想用这个,但是通过切换到'/,/'来更容易适应逗号分隔的方法。 – tadman 2014-11-06 18:56:28

+0

@CarySwoveland固定。感谢您注意到这一点。 – tadman 2014-11-06 21:10:37

0

这里是我的解决方案:

string = %w[ h e l l o ] 
indexes = '023' 

(
    0.upto(string.size - 1).to_a - 
    indexes.each_char.map(&:to_i) 
).each do |i| 
    string[i]= '_' 
end 

puts string.inspect 
# => ["h", "_", "l", "l", "_"] 
1
array.map.with_index{|x,i|!string.include?(i.to_s)?'-':x}