简体   繁体   English

array.select的语法是什么?

[英]What is the syntax for array.select?

I'm trying to use Array.select to separate out, and then delete, strings from a database that contain unwanted items. 我正在尝试使用Array.select从数据库中分离出包含不需要的项目的字符串,然后将其删除。 I get no errors but this does not seem to be working as hoped. 我没有收到任何错误,但这似乎并没有达到预期的效果。

The relevant code is the last part: 相关代码是最后一部分:

totaltext = []
masterfacs = ''
nilfacs = ''

roomfacs_hash = {'lcd' => lcd2, 'wifi'=> wifi2, 'wired' => wired2, 'ac' => ac2}
roomfacs_hash.each do |fac, fac_array| 
  if roomfacs.include? (fac) 
    totaltext = (totaltext + fac_array)
    masterfacs = (masterfacs + fac + ' ')
  else
    nilfacs = (nilfacs + fac + ' ')
  end
end

finaltext = Array.new
text_to_delete = totaltext2.select {|sentences| sentences =~ /#{nilfacs}/i}
finaltext = totaltext2.delete (text_to_delete)
puts finaltext

It's probably not working because delete isn't a chainable method (the return value is the object you are trying to delete on success, or nil if not found; not the modified array). 它可能无法正常工作,因为delete不是可链接的方法(返回值是您成功尝试删除的对象;如果未找到,则返回nil; 不是修改后的数组)。 To simplify your code, just use reject 为了简化您的代码,只需使用拒绝

finaltext = totaltext.reject{|sentence| nilfacs.any?{|fac| sentence =~ /#{fac}/i } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM