How do I remove an element from an array in a case-insensitive way?

时光毁灭记忆、已成空白 提交于 2019-12-12 03:52:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!