2011-12-03 99 views

回答

2

还有这个特殊的方法:

array.grep(/good/) # => ["Ham is good"] 

有了你可以做一个#grep很多,因为它需要一个正则表达式...

+2

这并不能解决将数组元素设置为其他值的问题。 – cvshepherd

+2

@maprihoda请注意,虽然'grep' _is_方便,但没有什么能阻止你用'select'或'find'来使用正则表达式(就像我的答案)。事实上,你可以用块方法做更多**,例如'select {| s | s =〜/ good/i && s.length> 3}'。 – Phrogz

+0

@Phrogz在正则表达式方面更多;尽管如此,你是对的,你可以用select做很多事情,你的评论中的第二个选择示例很好地说明了它 – maprihoda

13

既然没有答案到目前为止,指导您如何更新数组新值的字符串,这里有一些选择:

# Find every string matching a criteria and change them 
array.select{ |s| s.include? "good" }.each{ |s| s.replace("bad") } 

# Find every string matching a pattern and change them 
array.grep.replace("bad").each{ |s| s.replace("bad") } 

# Find the first string matching a criteria and change it 
array.find{ |s| s =~ /good/ }.replace("bad") 

然而,上述所有会改变一个字符串的所有实例。例如:

jon = Person.new "Johnny B. Goode" 
array = [ jon.name, "cat" ] 
array.find{ |s| s =~ /good/i }.replace("bad") 

p array #=> "bad" 
p jon #=> #<Person name="bad"> Uh oh... 

如果你不希望这个副作用,如果你想更换一个不同字符串数组中的字符串,而不是变化字符串本身,那么你需要找到该项目,并更新索引:

# Find the _first_ index matching some criteria and change it 
array[ array.index{ |s| s =~ /good/ } ] = "bad" 

# Update _every_ item in the array matching some criteria  
array[i] = "bad" while i = array.index{ |s| s =~ /good/i } 

# Another way to do the above 
# Possibly more efficient for very large arrays any many items 
indices = array.map.with_index{ |s,i| s =~ /good/ ? i : nil }.compact 
indices.each{ |i| array[i] = "bad" } 

最后,最简单和最快的大多是无摆弄指数:

# Create a new array with the new values 
new_array = array.map do |s| 
    if s =~ /good/i # matches "Good" or "good" in the string 
    "bad" 
    else 
    s 
    end 
end 

# Same thing, but shorter syntax 
new_array = array.map{ |s| s =~ /good/i ? "bad" : s } 

# Or, change the array in place to the new values 
new_array = array.map!{ |s| s =~ /good/i ? "bad" : s } 
2

map!听起来是一个不错的选择。

x = ['i', 'am', 'good'] 
def change_string_to_your_liking s 
    # or whatever it is you plan to do with s 
    s.gsub('good', 'excellente!') 
end 
x.map! {|i| i =~ /good/ ? change_string_to_your_liking(i) : i} 
puts x.inspect 
+0

好的答案,但请注意,OP从未说过有关更改字符串('gsub')的任何信息,它批发。 – Phrogz

+2

@Progrog这个问题是不是很清楚应该设置什么 – maprihoda

+0

Maprihoda是正确的。 OP说'把字符串设置成一个新的变量。对于我们所知的所有可能意味着从字符串中创建一个整数值。它可能确实需要更换,但没有明确说明。由于含糊不清,我没有假设变量修改的确切意图,并提供了一种方法,其内容可以很容易地根据他的喜好进行修改。请注意方法'change_string_to_your_liking'的名称和注释'#或者你打算用s'做什么。 – kikuchiyo

相关问题