DNorthrup
DNorthrup

Reputation: 847

Ruby Case Statement that keeps progressing

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?

Upvotes: 2

Views: 222

Answers (4)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

While @xdazz’ answer does the trick, it is not quite ruby idiomatic:

hash = %w|W R G U B|.map { |e| "{#{e}}"}
                    .zip(%w|White Red Green Blue Black|)
                    .to_h

print "Test a Color"
# color = gets.chomp
color = "Hello, {W}, I am {B}!"
puts color.gsub(Regexp.union(hash.keys), hash)
#⇒ Hello, White, I am Black!

We use here String#gsub(pattern, hash).

Upvotes: 1

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84453

Caveat

The following isn't the most efficient or idiomatic solution. However, it addresses your problem by making some simple improvements to your existing code while preserving your current semantics.

Loop Over Your Case Statement

This solution reads standard input and converts it into an Array object stored in colors, and then loops over the case statement for each element of that array.

print "Test a Color: "
colors = gets.chomp.scan /\{[WRGUB]\}/
colors.each do |color|
  case color
  when "{W}"
    puts "White"
  when "{R}"
    puts "Red"
  when "{G}"
    puts "Green"
  when "{U}"
    puts "Blue"
  when "{B}"
    puts "Black"
  end
end

This will result in output similar to the following:

$ ruby colors.rb 
Test a Color: {W}{B}
White
Black

Upvotes: 2

ndnenkov
ndnenkov

Reputation: 36110

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

input.scan(/{(\w)}/).each { |abbreviation| puts colors[*abbreviation] }

Upvotes: 2

xdazz
xdazz

Reputation: 160993

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 }

Upvotes: 7

Related Questions