On Thursday 28 August 2008 15:08:01 Thomas B. wrote:
> ALLOWED=[:foo,:bar]
> input=gets.downcase.chomp.to_sym
> if ALLOWED.include? input
> send(input)
> else
> puts "That isn't a command!"
> end
Subtle memory leak here: A symbol, once defined, is never collected. (Unless
this has changed, but I don't see how it could...) They have many advantages,
and I'd still use them in code, but don't use them with user input. Instead:
ALLOWED = %w{foo bar}.map(&:freeze).freeze
input = gets.downcase.chomp
if ALLOWED.include? input
send input
else
puts "'#{input}' isn't a command!"
end
A possible performance hack is to use a Set instead, but I'm not sure how
large the array has to be for this to actually be faster:
require 'set'
ALLOWED = Set.new(%w{foo bar}).freeze
And yes, "send" seems to work with strings. No point in casting to a symbol if
you're only going to be using it for one send call.
Of course, I wouldn't worry about it if you're only accepting input from one
user, at the commandline -- they'd have to bang on the keyboard quite awhile
to use any significant amount of RAM.
But it's something to consider when building any kind of long-running service.