I’m following along with a tutorial that’s building a hangman application in Ruby. It has a function masquerade which hides the word, which is just a country name that’s imported from a file. Problem is I don’t understand how this actually disguises the words, or how the ternary operator is working in inject. It’s checking if the character is blank (i.e. ” “), and, if it is, it’s setting it to blank (i.e. ” “), but if it’s not, it’s making it  . The function doesn’t seem to deal with the fact that the words have actual characters i.e. letters.
Can anyone explain for this sort of noob, what I’m misunderstanding? Also, why does it add ‘disguise’ again at the end (before the closing }?
def masquerade(word)
word.each_char.inject([]) { |disguise, char| disguise << (char == " " ? " " : " "); disguise }
end
Examples of game words
Afghanistan
Albania
Algeria
Andorra
Angola
Antigua & Deps
Argentina
Armenia
The whole Word class
class Word
class << self
def get_random
content = File.read("countries.txt")
words = content.split("\n")
words[rand(words.size)].upcase
end
def masquerade(word)
word.each_char.inject([]) { |disguise, char| disguise << (char == " " ? " " : " "); disguise }
end
def reveal(last_revealed_word, char_clicked, final_word)
chars = final_word.each_char.to_a
last_revealed_word.each_index do |i|
last_revealed_word[i] = chars[i] if last_revealed_word[i] == " " and chars[i] == char_clicked
end
end
def chars_left(revealed_word)
revealed_word.count { |c| c == " " }
end
end
end
Adding
disguiseat the end is not required. The<<already changes the object.You can see no difference:
upd: Masking here is to replace characters with non-breaking spaces