On Wed, Jul 4, 2012 at 2:18 AM, Sam Duncan <[email protected]> wrote:
> Or you could do;
>
> actor_data['biography'].empty?&& actor_data['biography'] = 'Biography not
> available'
Only that this won't work if actor_data is a Hash without default
value because NilClass#empty? does not exist:
irb(main):002:0> {}['biography'].empty?
NoMethodError: undefined method `empty?' for nil:NilClass
from (irb):2
from /opt/bin/irb19:12:in `<main>'
Methinks this is actually the best and most idiomatic way to do it:
actor_data['biography'] ||= 'Biography not available'
Better learn common idioms right from the start.
I do have another issue with this though: if that string is placed in
the Hash the information is lost that this value wasn't initially
available. IMHO it's much better to do the replacement when printing,
e.g.
%w{name biography country}.each do |field|
printf "%-20s: %s\n", field, actor_data[field] || "#{field} not available"
end
or just
%w{name biography country}.each do |field|
printf "%-20s: %s\n", field, actor_data[field] || 'not available'
end
Btw wutang, IRB is a great too to try these things out.
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en