我有一个方法,试图搜索定位与指定键和值匹配的每个记录的数组。
def search(key, query)
some_stuff = [{"title"=>"Awesome Book", "author"=>"John Doe", "qty"=>"5"}, {"title"=>"Another Book", "author"=>"Jane Doe", "qty"=>"2"}, {"title"=>"Ruby Book", "author"=>"John Hancock", "qty"=>"4"}]
# If I put the following in the block it will return has records
#however how do I substitute with key and query?
some_stuff.select {|b| b[].include? "jo" }
if matches.any?
# has records
else
# has no records
end
end
# If i call object.search(author, jo)
# I want to return the two records containing authors names with "jo" in them
# Similarly if I call object.search(title, rub)
# I want the query to return 1 record
另外,您将如何按指定字段对其进行排序
目前我正在考虑使用开关,但我几乎可以肯定有更简单的方法
答案 0 :(得分:1)
require 'pp'
SOME_STUFF = [
{"title"=>"Another Book", "author"=>"Jane Doe", "qty"=>"2"},
{"title"=>"Ruby Book", "author"=>"John Hancock", "qty"=>"4"},
{"title"=>"Awesome Book", "author"=>"John Doe", "qty"=>"5"},
]
def search(key, query)
SOME_STUFF.select {|record| record[key].downcase.include? query }
end
pp search('author', 'jo')
pp search('title', 'ru')
--output:--
[{"title"=>"Ruby Book", "author"=>"John Hancock", "qty"=>"4"},
{"title"=>"Awesome Book", "author"=>"John Doe", "qty"=>"5"}]
[{"title"=>"Ruby Book", "author"=>"John Hancock", "qty"=>"4"}]
另外,您将如何按指定字段对其进行排序
require 'pp'
SOME_STUFF = [
{"title"=>"Another Book", "author"=>"Jane Doe", "qty"=>"2"},
{"title"=>"Ruby Book", "author"=>"John Hancock", "qty"=>"4"},
{"title"=>"Awesome Book", "author"=>"John Doe", "qty"=>"5"},
]
def search(key, query)
SOME_STUFF.select do |record|
record[key].downcase.include? query
end.sort_by {|hash| hash[key]}
end
pp search('author', 'jo')
pp search('title', 'ru')
--output:--
[{"title"=>"Awesome Book", "author"=>"John Doe", "qty"=>"5"},
{"title"=>"Ruby Book", "author"=>"John Hancock", "qty"=>"4"}]
[{"title"=>"Ruby Book", "author"=>"John Hancock", "qty"=>"4"}]
编辑:
require 'pp'
class Book
def title
@title
end
def title=(val)
@title = val
end
attr_accessor :author, :qty #Same as above for author, qty
SOME_STUFF = [
Book.new("Ruby Book", "John Hancock", 4),
Book.new("Another Book", "Jane Doe", 2),
Book.new("Awesome Book", "John Doe", 5),
]
def search(key, query)
SOME_STUFF.select do |book|
book.send(key).downcase.include? query
end.sort_by {|book| book.send(key)}
end
pp search('author', 'jo')
pp search('title', 'ru')
--output:--
[#<Book:0x00000100929590 @author="John Doe", @qty=5, @title="Awesome Book">,
#<Book:0x00000100933270 @author="John Hancock", @qty=4, @title="Ruby Book">]
[#<Book:0x00000100933270 @author="John Hancock", @qty=4, @title="Ruby Book">]
send()方法接受一个字符串/符号(或包含字符串/符号的变量)作为参数,然后send()基本上说,“嘿ruby,调用我在左边的对象上指定的方法。 “当你拥有所有方法时,需要在对象上调用方法名称作为字符串在许多编程语言中很常见。 ruby为我们发送了send()。