问题
I’m suing Ruby 2.3. When I want to remove a string element from an array by value, I can do
2.3.0 :005 > a.delete("AB")
=> "AB"
but how do I remove the element in a case-insensitive way? That is, how can I make
a.delete(“ab”)
behave like
a.delete(“AB”)
?
回答1:
Try delete_if
a.delete_if { |s| s.downcase == 'ab' }
回答2:
Your question says "remove an element" which implies you only want to remove one element when duplicates exist. If that is your intent (and there may be duplicates), you can remove the first or last instance thusly:
arr = ['aB', 'cd', 'Ab', 'ef']
def delete_first(arr, target)
ndx = arr.index { |s| s.downcase == target }
ndx.nil? > nil : arr.delete_at(ndx)
end
delete_first(arr, 'ab')
#=> "aB"
arr
#=> ["cd", "Ab", "ef"]
delete_first(arr, 'de')
#=> nil
arr
#=> ["aB", "cd", "Ab", "ef"]
To delete the last instance of target
in arr
simply replace index
with rindex
.
See Array#delete_at, Array#index and Array#rindex.
回答3:
a.reject!{|str| str.casecmp("AB").zero?}
casecomp
is the case-insensitive version of String#<=>
.a.reject!{|str| str.casecmp("ab").zero?}
behaves exactly the same.
回答4:
You can use Array#reject instead, like this:
bad_string_downcase = bad_string.downcase
a.reject! { |element| element.downcase == bad_string_downcase }
Or using regex:
a.reject! { |element| element.match %r{^#{bad_string}$}i }
来源:https://stackoverflow.com/questions/40962598/how-do-i-remove-an-element-from-an-array-in-a-case-insensitive-way