Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to filter two strings into 1 in ruby

I am trying to figure out a way to filter two arrays into one based on guessing the letters within one o them.. so basically hangman. But if I had

word_array = ["b", "u", "s", "b", "o", "i"]
hidden_array = Array.new(word_array.length, "-")

p hidden_array

I would want to then print to the console ["b", "-", "-", "b", "-", "-"] if "b" were guessed. What would be a good beginner way to create this array that will change over time? Should it maybe be a hash? Thanks!

like image 743
Rob Matthews Avatar asked Nov 21 '25 08:11

Rob Matthews


2 Answers

All of the solutions so far revolve around arrays, but don't forget a string is basically a character array anyway. Just use strings:

word = 'busboi'
guesses = 'bs'

word.tr('^'+guesses, '-')
# => "b-sb--"

The String#tr method converts all letters in the first argument to the mapping in the second argument, so you can do things like ROT13, simple cyphers and such, or in this case use the negation feature ^ to invert the first set and replace all non-matching characters.

like image 104
tadman Avatar answered Nov 23 '25 02:11

tadman


You can keep track of the found letters in an array and make a method to do the printing

word_array = ["b", "u", "s", "b", "o", "i"]
found_letters = []
def hangman_prompt(found_letters)
  word_array.map do |char|
    found_letters.include?(char) ? char : "-"
  end.join(" ")
end

Then you could use this in an input loop like so:

loop do
  puts hangman_prompt(found_letters)
  puts "what is your guess?"
  input = gets.chomp
  if word_array.include? input
    found_letters << input
  end
end

I'm using Array#map here which creates a new array of the same length. Each of the original array items are passed to the block, which determines how they could be copied to the new array.

like image 30
max pleaner Avatar answered Nov 23 '25 00:11

max pleaner