Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Case Statement that keeps progressing

Tags:

ruby

I'm trying to convert special symbols ({W} {B} {U} etc) to their respective color so I wrote a CASE but I'm thinking a case isn't what I need since it ends as soon as it finds a match.

print 'Test a Color'
color = gets.chomp

case color
when '{W}'
  puts 'White'
when '{R}'
  puts 'Red'
when '{G}'
  puts 'Green'
when '{U}'
  puts 'Blue'
when '{B}'
  puts 'Black'
end

{B} gets me Black, {U} gets my Blue. {U}{B} crashes it/returns nothing. How would I go about letting it continue down the list?

like image 727
DNorthrup Avatar asked Jan 18 '26 15:01

DNorthrup


2 Answers

Check below.

print "Test a Color"
color = gets.chomp

hash = {
  '{W}' => 'White',
  '{R}' => 'Red'
}

# finding by regex and replace with what you want.
puts color.gsub(/\{.+?\}/){|k| hash[k] || k }
like image 128
xdazz Avatar answered Jan 20 '26 13:01

xdazz


colors = {
  'W' => 'White',
  'R' => 'Red',
  'G' => 'Green',
  'U' => 'Blue',
  'B' => 'Black',
}

input.scan(/{(\w)}/).each { |abbreviation| puts colors[*abbreviation] }
like image 44
ndnenkov Avatar answered Jan 20 '26 13:01

ndnenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!