How to return the vaue of a specified hash key in an array in ruby? -
i have method attempts search array locating each record matching specified key , value.
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 put following in block return has records #however how substitute key , query? some_stuff.select {|b| b[].include? "jo" } if matches.any? # has records else # has no records end end # if call object.search(author, jo) # want return 2 records containing authors names "jo" in them # if call object.search(title, rub) # want query return 1 record
also, how sort specified field
currently i'm thinking using case switch i'm sure there easier way
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"}]
also, how sort specified field
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.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"}]
edit:
require 'pp' class book def title @title end def title=(val) @title = val end attr_accessor :author, :qty #same above 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 |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">]
the send() method takes string/symbol (or variable containing string/symbol) argument, send() says, "hey ruby, call method specified on object left." need call method on object when have method name string common in lots of programming languages. ruby gives send() that.
Comments
Post a Comment