Justin Collins
11/17/2006 7:18:00 AM
Scott Comboni wrote:
> Hello all,
> Nuby question?
> I need to parse the syntax on files based on a two charcter code such as
> PC which would return a value like this PC = Postcard I have many many
> codes and Im very new to Ruby and not sure what the best way to do this
> is and performance considerations? So would multiple if statements be a
> better ruby way then using case or does it mater?
>
> example:
> file name: d123456_PC_xxxxx.pdf
>
> filename.split('_')[1]
>
> case component
> when "PC": puts "Postcard"
> when "DC": puts "Decal"
> else
> puts "n/a"
> end
>
> or
>
> or am i better using
> if component == 'PC': puts "Postcard"
> elsif component == 'DC': puts "Decal"
>
> ....et
I would certainly use a case statement over a bajillion if statements.
You could also (depending on your problem) put all the codes in a hash
table and just do a lookup that:
codes = { "PC" => "Postcard",
"DC" => "Decal",
...etc }
filenames.each do filename
puts codes[filename.split("_")[1]]
end
Or similar.
-Justin