A similar problem:
case key.strip
when "c" "Synopsis"
when "s" "Category"
when "io" "Inputs and outputs"
when "processing" "Processing type"
when "d" "Description"
when "n" "Notes"
when "e" "Examples"
when "h" "Element handlers"
when "a" "See also"
else puts "Unknown key"
end
if key.strip == "a"
puts "This gives output"
end
unknown key
This gives output
What am I doing wrong? I'm a really Ruby newbie so probably I'm looking at
it the wrong way...
case key.strip
when "c" "Synopsis"
when "s" "Category"
when "io" "Inputs and outputs"
when "processing" "Processing type"
when "d" "Description"
when "n" "Notes"
when "e" "Examples"
when "h" "Element handlers"
when "a" "See also"
else puts "Unknown key"
end
if key.strip == "a"
puts "This gives output"
end
unknown key
This gives output
What am I doing wrong? I'm a really Ruby newbie so probably I'm looking at
it the wrong way...
You forget to put "puts" before you're Strings. This will work:
case key.strip
when "c" puts "Synopsis"
when "s" puts "Category"
...
end
And this will also work and require less repetition:
puts case key.strip
when "c": "Synopsis"
when "s": "Category"
...
end
Though I wonder if you're not better of with a Hash:
And this will also work and require less repetition:
puts case key.strip
when "c": "Synopsis"
when "s": "Category"
...
end
Actually the code has less duplication, this was just an example. But why
doesn't this work:
def keyToName(key)
case key.strip
....
when "h" "Element handlers"
when "a" "See also"
else "Unknown key"
end
end
puts keyToName("a")
puts keyToName('a')
It gives "Unknown key" twice, instead of "See also" at least once.
Though I wonder if you're not better of with a Hash:
Actually the code has less duplication, this was just an example. But why
doesn't this work:
def keyToName(key)
case key.strip
...
when "h" "Element handlers"
when "a" "See also"
else "Unknown key"
end
end
puts keyToName("a")
puts keyToName('a')
It gives "Unknown key" twice, instead of "See also" at least once.
Hah, I knew that you weren't supposed to use when like that. You're actually doing this with the above code:
case key.strip
when "hElement handlers"
when "aSee also"
else "Unknown key"
end
Which of course isn't what you want. Put a "then" or ":" between the condition and the action parts and it will work.
Though I wonder if you're not better of with a Hash: