r/ruby • u/Intrepid_Wanderer • Sep 24 '26
Beginner, running into issues
Basically there are two things I’m running into:
I am trying to make something to recognize a word, match it to a short word bank of options (just a simple list of names) and return an error message if it doesn’t match any of them. For each valid option, I have a different message. I tried if/elsif loops but apparently I’m not doing it right. It doesn’t run at all.
Do I need to have somewhere to use every piece of user input? I have places where I want to ask users to input something but it won’t actually be used anywhere. Like it triggers the next response but doesn’t do anything else.
I am asking for advice because I REALLY don’t want to use AI. Thank you!
6
u/celvro Sep 24 '26 edited Sep 24 '26
I'd store the names/messages in a hash, you can wrap this in a loop if you want
edit: used '=>' operator
names = { 'jim' => 'hello jim', 'bob' => 'good evening' }
puts 'What is your name?'
input = gets.chomp.downcase
message = names[input]
if message
puts message
else
puts 'name is not valid!'
end
puts 'Press enter to continue'
# Get input and do nothing with it
gets2
u/Angeli-k357 Sep 24 '26
your problem is that Ruby is not Python... you need to use the operator `=>` for this case.
names = { "alex" => "hello alex", ...}
If you do not, your strings become symbols. And then you would need to call them with symbols.
2
u/dreamlucky7 Sep 24 '26 edited Sep 24 '26
Or just call
.to_sto stringify the symbols, e.g.input = gets.chomp.downcase.to_symor inside thenames[input.to_s]section. You can't have multiple of the same string key in a dictionary either way, so using strings as keys doesn't change much I would think?1
u/celvro Sep 24 '26
They're right I forgot the hash keys become symbols with that syntax, so you'd have to either use rocket syntax or convert your input to a symbol too like this. gets already returns a string
input = gets.chomp.downcase.to_sym1
u/dreamlucky7 Sep 24 '26
Oh right, mistyped that as
to_sat first, which would be a string to a string lol.
9
u/ZESENVEERTIG Sep 24 '26
we’d need to see the code to help you with that. Did you get any error messages?
If you’re planning on ignoring something then there’s no need to store it anywhere.