2014-11-06 154 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}