Forum: Ruby Better way to do this?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
953d32e245f7eb0e670bde0577f1eb43?d=identicon&s=25 Pito Salas (pitosalas)
on 2009-02-12 23:26
Hi,

I seem to be repeating myself in the following little bit:

if (!@options[:namespace].nil?)
    namespace_options = @options[:namespace]
    root.add_namespace(namespace_options[:namespace],
namespace_options[:value])
end

Can someone show me a way to not repeat options[:namespace] ?

Simpler example of the exact same:

if (!hash[:value].nil?)
    h = hash[:value]
    puts h[:left], h[:right]
end

Thanks for any tips for writing more idiomatic ruby!
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2009-02-12 23:47
(Received via mailing list)
Pito Salas wrote:
> Can someone show me a way to not repeat options[:namespace] ?
>
> Simpler example of the exact same:
>
> if (!hash[:value].nil?)
>     h = hash[:value]
>     puts h[:left], h[:right]
> end

hash = {
   :value => {:left => 1, :right => 2}
}

# original:
if (!hash[:value].nil?)
     h = hash[:value]
     puts h[:left], h[:right]
end

# looking up :value only once
h = hash[:value]
if h ## assuming you don't use false as a value in the hash
   puts h[:left], h[:right]
end

# living a little dangerously (assignment in conditional):
if (h = hash[:value])
   puts h[:left], h[:right]
end

# more compactly, if you care:
h = hash[:value] and puts h[:left], h[:right]

# the last one depends on 'and' having low precedence (unlike &&)
C06869c119472a139eb163b72040b0db?d=identicon&s=25 Bertram Scharpf (Guest)
on 2009-02-12 23:48
(Received via mailing list)
Hi,

Am Freitag, 13. Feb 2009, 07:24:59 +0900 schrieb Pito Salas:
>
> if (!hash[:value].nil?)
>     h = hash[:value]
>     puts h[:left], h[:right]
> end

Untested:

  if (!(h = hash[:value]).nil?)
    puts h[:left], h[:right]
  end

or

  h = hash[:value]
  unless h.nil? then
    puts h[:left], h[:right]
  end

or

  h = hash[:value]
  h.nil? or puts h[:left], h[:right]

Hope you enjoyed the trip.

Bertram
4d5b5dd4e263d780a5dfe7ac8b8ac98c?d=identicon&s=25 Tim Pease (Guest)
on 2009-02-12 23:50
(Received via mailing list)
On Feb 12, 2009, at 3:24 PM, Pito Salas wrote:

> Can someone show me a way to not repeat options[:namespace] ?
>
> Simpler example of the exact same:
>
> if (!hash[:value].nil?)
>    h = hash[:value]
>    puts h[:left], h[:right]
> end
>

if (h = hash[:value])
   puts h[:left], h[:right]
end


Blessings,
TwP
This topic is locked and can not be replied to.