Reputation: 39
Creating a method that receives input from a user -- and if said input includes any word from a predetermined array, it prints the word "success!" Otherwise, if the input doesn't include a word from that array, it prints the word "failure."
My ideal would be to create a scenario where I can populate the array with as many elements as I want, and the method will always reference that array when deciding how to react to the user's input.
When I run it, however, I get an error message saying "no implicit conversion of Array into String."
My code is below. Appreciate any and all help! Thanks.
def hello
word_bank = ["hello", "hi", "howdy"]
print "Say a word: "
greeting = $stdin.gets.chomp.to_s
if greeting.include?(word_bank[0..2])
puts "success!"
else
puts "failure."
end
end
hello
Upvotes: 1
Views: 113
Reputation: 30056
include?
is an array's method.
word_bank = ["hello", "hi", "howdy"]
print "Say a word: "
greeting = gets.chomp
if word_bank.include?(greeting)
puts "success!"
else
puts "failure."
end
puts [1,2,3].include?(1) # true
puts [1,2,3].include?(4) # false
If word_bank
was big, for performance reason we should use a set instead of an array.
require 'set'
word_bank = Set.new(["hello", "hi", "howdy"])
Upvotes: 3
Reputation: 1674
This is how I'd solve the issue, I haven't tested it though but it should work.
def hello
word_bank = ['hello', 'hi', 'howdy']
print 'Say a word: '
greeting = $stdin.gets.chomp.to_s
word_bank.each do |w|
w == greeting ? (puts 'success') : (puts 'failure')
end
end
Upvotes: 0