Non-literal hash elements in argument list?

Many Rails helpers use an idiomatic options hash as their last argument;
Ruby automatically inserts extra method arguments into that hash. I
often find myself wanting to conditionally insert an element, or to
write a helper that provides the element. Two examples in pseudo-Ruby:

    link_to "Example 1", "http://www.example.com", needs_confirmation? ?
:confirm => "Are you sure?" : nil # syntax error; nil can't be a hash
element

or

    link_to "Example 2", "http://www.example.com", unique_link_id

    # I don't want to return a hash; I want to return an element of a
hash
    def unique_link_id
      :id => "our_link_#{user.id}" # Syntax error
      {:id => "our_link_#{user.id}"} # valid, but returns a hash that
ends up being an element of the options hash
      {:id => "our_link_#{user.id}"}.flatten_into_my_parent_hash #
What's in my brain
    end

Is there some elegant way to do this? I can build the hash as a variable
before the method call, of course, and optionally add elements, but...
ick.

Let's stipulate that these are contrived examples, and assume that the
helpers wouldn't allow :confirm => nil or :id => nil, and that
unique_link_id might want to leave off the ID, and that I can't control
the helper I'm calling. I'm more interested in the Ruby hash syntax than
in solving a Rails problem.

Is this a possible thing?

···

--
Posted via http://www.ruby-forum.com/.

I'm pretty sure you just want Hash#merge.

-- Matma Rex

Jay Levitt wrote in post #1018816:

Is there some elegant way to do this? I can build the hash as a variable
before the method call, of course, and optionally add elements, but...
ick.

That is the elegant, clear way to do it. What you came up with belongs
in a code obfuscation contest. If writing code like that is your idea
of a good time, learn perl and have at it.

···

--
Posted via http://www.ruby-forum.com/\.

Bartosz Dziewoński wrote in post #1018817:

I'm pretty sure you just want Hash#merge.

You know, I think you're right - I never thought of it like that.

    link_to "Example 1", "http://www.example.com", {:some =>
:option}.merge(needs_confirmation? ?
{:confirm => "Are you sure?"} : {}}

    link_to "Example 2", "http://www.example.com", {:some =>
:option}.merge(unique_link_id)

    def unique_link_id
      {:id => "our_link_#{user.id}"}
    end

Thanks for removing my mental block.

···

--
Posted via http://www.ruby-forum.com/\.