1

Rails fans are familiar with params[:terms] or a hash of 'things' passed to the controller collected form the url. E.g.:

params
=> {"term"=>"Warren Buffet",
    "controller"=>"search",
    "format"=>"json",
    "action"=>"index"}

If I want to use "Warren Buffet", "Warren" and "Buffet" in the code below, does anyone know which method I should be using instead? gsub is close, but it takes each match and not the original string too. Unless I'm doing it wrong, which is totally possible:

@potential_investors = []
params[:term].gsub(/(\w{1,})/) do |term|
  @potential_investors << User.where(:investor => true)
  .order('first_name ASC, last_name ASC')
  .search_potential_investors(term)
end

Thoughts?

4

2 回答 2

2

怎么样:

s = "Filthy Rich"
s.split(" ").push(s)
>> ["Filthy", "Rich", "Filthy Rich"]

或者,scan如果您更喜欢使用正则表达式:

s.scan(/\w+/).push(s)
>> ["Filthy", "Rich", "Filthy Rich"]
于 2012-05-28T23:11:24.953 回答
1
params["term"].gsub(/(\w{1,})/)

返回一个枚举器。您可以将其转换为数组并将原始术语附加到其中:

ary = params["term"].gsub(/(\w{1,})/).to_a + [params["term"]]

然后处理它:

ary.each do |term|
...
于 2012-05-28T23:11:19.067 回答