-1

I have a ruby method that queries a array through a search. From what is typed in the searchbar it appends that item to another array that shows on the screen. Below is my method:

@churches = ["UGBC", "Oak Ridge Baptist", "Calvary"]
@search_results = []


def search_for(text)
  @churches.collect do |church|
    if text == church
      @search_results << church
    end
  end
end

When the code is triggered the only object that is returned when searched is the last object in the array: "Calvary". If you search any of the other items it sends back an empty array. I have tried an each statement and a collect statement and nothing will work. How do I get it to append to the empty array with no matter what item I search on?

Jason Milam
  • 101
  • 2
  • 14
  • 3
    Working with side-effects is usually a bad idea, if besides that the operation done is not idempotent (`<<`), it's conceptually pretty bad. – tokland Jul 18 '13 at 10:52

3 Answers3

1

You are not using the right method. I think Array#select is what you need. Also you might have to do a substring check for the text.

Here is an example

text = 'Ridge'

> churches.select{|c| c.include?(text)}
#=> ["Oak Ridge Baptist"]
Santhosh
  • 28,097
  • 9
  • 82
  • 87
  • The select method was exactly what I was looking for. Now I can append the results into a new array every time. Thanks a lot. – Jason Milam Jul 18 '13 at 12:50
0

What is your text value?. If you are performing text("Calvary") == church.. It matches one of the element of @churches.That @churches element alone store in @search_results. So storing last element.

Inaccessible
  • 1,560
  • 3
  • 18
  • 42
0

Your function returns the value of the last expression evaluated. That is the value of @churches.collect. That -- in turn -- is an array of the three values of the block:

search_for('UGBC')               # => [["UGBC"], nil, nil]
@search_results = []
search_for('Oak Ridge Baptist')  # => [nil, ["Oak Ridge Baptist"], nil]
@search_results = []
search_for('Calvary')            # => [nil, nil, ["Calvary"]]
@search_results = []
search_for('something else')     # => [nil, nil, nil]

The block yields nil in case of no match and @search_result with the found church appended in case of a match.

Note that your function modifies @search_results. So I reset it in order to hide the side-effects of previous runs.

An obvious fix to your function is to return @search_results:

def search_for(text)
  @search_results = []
  @churches.collect do |church|
    if text == church
      @search_results << church
    end
  end
  @search_results # or even: return @search_results
end

A better implementation returning the found element or nil is

def search_for(text)
  @churches.find { | c | c == text }
end
undur_gongor
  • 15,657
  • 5
  • 63
  • 75