所以我正在ruby中创建一个类,在那里我可以将数据插入文本文件中,然后从中读取,查找,但是我被困在删除以及更新/编辑上。
基本上,我创建了一个名为“ find”的方法,并将其作为“ delete”方法的参考。
def find(keyword="")
if keyword
person = People.read_people
found = person.select do |pip|
pip.name.downcase.include?(keyword.downcase) ||
pip.age.downcase.include?(keyword.downcase) ||
pip.country.downcase.include?(keyword.downcase)
end
found.each do |person|
puts person.name + " | " + person.age + " | " + person.country
end
else
puts "find using a key phrase eg. 'find sam' \n\n"
end
end
def list
puts "\nListing People \n\n".upcase
people = People.read_people
people.each do |person|
puts person.name + " | " + person.age + " | " + person.country
end
end
def delete(keyword="")
if keyword
person = People.read_people
found = person.select do |pip|
pip.name.downcase.include?(keyword.downcase) ||
pip.age.downcase.include?(keyword.downcase) ||
pip.country.downcase.include?(keyword.downcase)
end
person.delete(found)
else
puts "find using a key phrase eg. 'find josh' \n\n"
end
end
如您所见,我正在尝试通过名为read_people的类方法从数组中删除提供的关键字(w / c保存在文本文件中)。外观如下:
def self.read_people
# read the people file
# return instances of people
people = []
if file_usable?
file = File.new(@@filepath, 'r')
file.each_line do |line|
people << People.new.import_line(line.chomp)
end
file.close
end
return people
end
def import_line(line)
line_array = line.split("\t")
@name, @age, @country = line_array
return self
end
如何解决此问题并通过关键字删除找到的项目?
在此处查看实际代码:https://repl.it/repls/VastWildFact
答案 0 :(得分:2)
更改
person.delete(found)
到
person -= found # Equivalent to person = person - found
它应该按照https://ruby-doc.org/core-2.2.0/Array.html#method-i-2D
运行
ary - other_ary → new_ary
返回一个新数组,该数组是原始数组的副本,并删除也出现在other_ary中的所有项目。该顺序保留在原始数组中。
它使用哈希和eql比较元素?效率的方法。
示例:[1,1,2,2,3,3,4,5]-[1,2,4]#=> [3,3,5]
另一种解决方案是按如下方式使用reject
:
person.reject! do |pip|
pip.name.downcase.include?(keyword.downcase) ||
pip.age.downcase.include?(keyword.downcase) ||
pip.country.downcase.include?(keyword.downcase)
end
答案 1 :(得分:2)
基本上,您将需要一种看起来像这样的export_people
和write_people
方法:
def self.export_people(people)
people.map do |person|
[person.name, person.age, person.country].join("\t")
end
end
def self.write_people(people)
File.new(@@filepath, 'w') do |f|
f.write(export_people(people))
end
end
# Usage:
Person.write_people(array_of_people)
使用上面的代码,您将调用modified delete
method as detailed in Tarek's answer,然后调用Person.write_people(array_of_people)
写回文件。