0

My goal is to have the user enter a string to find a string in an array. Im using strings include? function to search but its returning the wrong data.

 puts "Enter Artist(all or partial name):"   
 search_artist = gets.chomp
 list.each do |x|
     if x.artist.include? (search_artist)
       num += 1
       x.to_s
     else
       puts "none found"
     end   end

search_artist = 'a' (because im looking for AARON...)

returns:

AARON KDL NOT VALID 2
ZAC CHICKEN ROCK 1289
2 records found

should be:

AARON KDL NOT VALID 2     
1 record found`

The problem is that both strings include 'a' somewhere in the string. How do I search from the beginning of the string?

4
  • 1
    Pretty much a duplicate: stackoverflow.com/q/4130364/1531971 Commented Nov 5, 2018 at 19:55
  • The indentation here is extremely chaotic and it's making the code hard to follow. Remember to clean up your code, especially when asking on Stack Overflow. It helps us establish intent. Commented Nov 5, 2018 at 19:59
  • 2
    Try changing include? to String#start_with?. Commented Nov 5, 2018 at 20:26
  • Possible duplicate of Does Ruby have a string.startswith("abc") built in method? Commented Nov 5, 2018 at 21:12

3 Answers 3

3

There's a really easy way of doing this with grep:

matches = list.grep(search_artist)

if (matches.empty?)
  puts "none found"
end

To count the number of matches you can just matches.length.

If you want a case insensitive match, then you want this:

matches = list.grep(Regexp.new(search_artist, Regexp::IGNORECASE))

Where that flag creates a case-insensitive regular expression to match more broadly.

Edit: To anchor this search to the beginning of the string:

matches = list.grep(Regexp.new('\A' + Regexp.escape(search_artist), Regexp::IGNORECASE))

Where \A anchors to the beginning of the string.

Sign up to request clarification or add additional context in comments.

1 Comment

@moveson As Carey pointed out, the request was actually for "search from the beginning of the string" so it needs the \A anchor.
0

Other option, just if the search is limited to the first letter, case insensitive:

found = list.select { |x| [search_artist.downcase, search_artist.upcase].include? x[0] }
found.each { |e| puts e }
puts "Found #{found.size} records"

Comments

0

Without Regular expressions:

puts "Enter Artist(all or partial name):"   
search_artist = gets.chomp

puts list.select do |x|
  x.artist.start_with?(search_artist)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.