Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
假设我有这个数组:
array = ["str1", "str2", "str3", "str4", "str5", "str6", "str7", "str8"]
我在做什么:
array.delete_if {|i| i == "str1" || i == "str3" || i == "str5"}
我有:
["str2", "str4", "str6", "str7", "str8"]
ruby 有没有更好的方法来做到这一点?
你可以这样做:
array - %w{str1 str2 str3}
请注意,这会返回一个带有"str1"、"str2"和的新数组"str3",而不是array直接修改(就像delete_if那样)。array您可以像这样简洁地重新分配新数组:
"str1"
"str2"
"str3"
array
delete_if
array -= %w{str1 str2 str3}
array.reject{|e| e=~ /str[135]/}