I have a method that checks if a word includes a certain letter. The string#include? method’s supposed to return true if the string object contains the letter in any position. However, my method is only returning true if there’s a match between the letter (char_clicked) and the letter at the first position of the word (final_word). For example, if the final_word parameter is Spain, the method is only returning true if “S” is the char_clicked, it’ll return false if char_clicked is any of “_pain”
Can you please ease my pain and tell me what I’m doing wrong…
def correct_guess?(char_clicked, final_word)
puts char_clicked, final_word #p, Spain
puts final_word.is_a?(String) #true
puts "checking if string"
puts final_word.include?(char_clicked) #false
final_word.include?(char_clicked)
end
Update
I’m getting the same result even if I turn the string into an array and check for the letter
puts final_word.split("").include?(char_clicked)
However, if I use include in the console for that application, it works fine
>> s = "brazil"
=> "brazil"
>> s.include?("z")
=> true
Seeing as the first response to this question confirms that include? should be working the way I’ve shown it above, I’m providing more information which might hopefully explain why it’s not working as one would expect
The final_word is being pulled out of the session before being sent to the correct_guess? method for checking. The char_clicked is pulled out of the parameters
def check
final_word = session[:word]
char_clicked = params[:char_clicked]
correct_guess = Game.correct_guess?(char_clicked, final_word)
....
Ajax request sending the char_clicked to the above check method
$.ajax({
url: "/check",
type: "POST",
data: {char_clicked: this.get("char_clicked")},
success: function(response) {
console.log(response);
var json = $.parseJSON(response);
if (response.incorrect_guesses >= _this.get("threshold")) _this.set({lost: true});
if (response.win) _this.set({win: true});
_this.trigger("guessCheckedEvent", response);
}
})
},
Maybe
include?is overridden somewhere (monkeypatched). Does the following work?It’s unlikely that the regex-matcher method is overridden, too.