在ruby中使用find_all查找不区分大小写的记录

在ruby中使用find_all查找不区分大小写的记录,ruby,Ruby,我需要使用find\u all方法从多行csv中提取记录 假设csv有员工和经理姓名的记录 @csv_table = CSV.parse(data, headers: true) @results = @csv_table.find_all { |row| row['Employee'].start_with? @text } 我只能在Employee列中找到记录,但不知道如何从Employee和Manager列中搜索,也不知道如何使用不区分大小写的条件来解决这两个Employee和Manag

我需要使用
find\u all
方法从多行csv中提取记录

假设csv有
员工
经理
姓名的记录

@csv_table = CSV.parse(data, headers: true)
@results = @csv_table.find_all { |row| row['Employee'].start_with? @text }

我只能在
Employee
列中找到记录,但不知道如何从
Employee
Manager
列中搜索,也不知道如何使用不区分大小写的条件来解决这两个Employee和Manager匹配问题,在块中使用双条件:

@results = @csv_table.find_all do |row|
  row['Employee'].start_with? @text || row['Manager'].start_with? @text
end
不敏感问题可通过两种方式解决:通过下套管(或上套管)比较每根管柱:

searchable_text = @text.downcase
@results = @csv_table.find_all do |row|
  row['Employee'].downcase.start_with? searchable_text ||
    row['Manager'].downcase.start_with? searchable_text
end
或者以更优雅的方式使用不敏感的正则表达式:

regex = /^#{@text}/i # notice the ^ to mimic the start_with?
@results = @csv_table.find_all do |row|
  row['Employee'].match? regex || row['Manager'].match? regex
end

根据内容的不同,正则表达式的行为可能与
start\u with?
稍有不同,但对于名称,它应该是可以的。

在该块中,员工和经理都匹配,并用双条件解决:

@results = @csv_table.find_all do |row|
  row['Employee'].start_with? @text || row['Manager'].start_with? @text
end
不敏感问题可通过两种方式解决:通过下套管(或上套管)比较每根管柱:

searchable_text = @text.downcase
@results = @csv_table.find_all do |row|
  row['Employee'].downcase.start_with? searchable_text ||
    row['Manager'].downcase.start_with? searchable_text
end
或者以更优雅的方式使用不敏感的正则表达式:

regex = /^#{@text}/i # notice the ^ to mimic the start_with?
@results = @csv_table.find_all do |row|
  row['Employee'].match? regex || row['Manager'].match? regex
end

根据内容的不同,正则表达式的行为可能与
start\u with?
稍有不同,但对于名称,它应该是可以的。

您可以写:
select\u headers=['Employee',Manager']。。。。查找|全部执行|行|选择|标题。有吗?{| header | header[row].match?regex}
。这样,如果要更改,您只需更改
select_headers
。。。。查找|全部执行|行|选择|标题。有吗?{| header | header[row].match?regex}。这样,如果要更改标题,只需更改
选择标题。