Sylar
Sylar

Reputation: 12072

Getting a value from a string

I am trying to match one or more keywords within a string (str), but I have no luck. My method below is trying to match all keys when I only needed to match any (one or more).

@str = "g stands for girl and b is for boy"

def key1
 %w[a, b, c, d, f, g]
end    

def result
 if @str.include?( key1 )
  puts "happy days"
 else
  puts "bad days"
 end
end

puts result # => bad days

How to make it show "happy days"?

PS: I have no idea what to name this title to. Maybe a mod could rename it?

Upvotes: 0

Views: 58

Answers (3)

Anthony
Anthony

Reputation: 15957

You're asking if your string includes the Array: ["a", "b", "c", "d", "f", "g"]

What I think you're trying to ask is this: are there any elements in the array that also exist in the string? This is a good use case for Enumerable#any like this:

[2] pry(main)> @str = "g stands for girl and b is for boy"
=> "g stands for girl and b is for boy"
[3] key1 = %w[a b c d f g]
=> ["a", "b", "c", "d", "f", "g"]
[4] pry(main)> key1.any? { |letter| @str.include?(letter) }
=> true

So to refactor your code, it might look like this:

@str = "g stands for girl and b is for boy"

def key1
 %w[a b c d f g]
end    

def result
 if key1.any? { |letter| @str.include?(letter) }
  puts "happy days"
 else
  puts "bad days"
 end
end

Something to note, with %w you don't need to use commas, you can simply separate the letters by a space (as outlined above).

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110655

I would use a regular expression:

MAGIC_CHARS = %w[a b c d f g]
  #=> ["a", "b", "c", "d", "f", "g"]

def result(str)
  (str =~ /#{MAGIC_CHARS.join('|')}/) ? "happy days" : "bad days"
end

result("g stands for girl and b is for boy")
  #=> "happy days" 
result("nothin' here")
  #=> "bad days" 

Note:

/#{MAGIC_CHARS.join('|')}/
  #=> /a|b|c|d|f|g/ 

You could instead write:

Regexp.union(MAGIC_CHARS.map { |c| /c/ })
  #=> /(?-mix:c)|(?-mix:c)|(?-mix:c)|(?-mix:c)|(?-mix:c)|(?-mix:c)/

or

/[#{MAGIC_CHARS.join('')}]/
  #=> /[abcdfg]/ 

Another way:

def result(str)
  (str.chars & MAGIC_CHARS).any? ? "happy days" : "bad days"
end

result("g stands for girl and b is for boy")
  #=> "happy days" 
result("nothin' here")
  #=> "bad days" 

Upvotes: 1

iced
iced

Reputation: 1572

I can't clearly understand your question, but I suspect you are looking for following:

key1.find { |k| @str.include? k }

Upvotes: 1

Related Questions