Forum: Ruby Hash is not merged / recursive function

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.
Dominik K. (Guest)
on 2009-01-05 16:35
Hi,

i'm new to ruby, but i really like it.

I'm trying to extend Ruby on Rails FormHelper with a custom function
which returns a recursive tree select field for "acts_as_tree"-models.

My Problem is, that the hash is not being merged correctly and so i only
get values which are up to the root of the tree.

Thanks for all answers.

Here's my code:

module ActionView
  module Helpers
    class FormBuilder
      def tree_select_options(collection, value_method, text_method,
level = 0)
        choices = {}
        collection.map do |element|
          choices[" " * level + element.send(text_method)] =
element.send(value_method)
          if (element.children.size > 0)
            choices.merge(tree_select_options(element.children,
value_method, text_method, level+5))
          end
        end
        return choices
      end

      def tree_select(method, collection, value_method, text_method,
options = {}, html_options = {})
        choices = tree_select_options(collection, value_method,
text_method)
        @template.select(@object_name, method, choices,
options.merge(:object => @object), html_options)
      end
    end
  end
end
Robert D. (Guest)
on 2009-01-05 18:21
(Received via mailing list)
On Mon, Jan 5, 2009 at 3:35 PM, Dominik Krebs
<removed_email_address@domain.invalid> wrote:
I have no idea what's wrong with your code, but I happen to know a
Ruby Guru, so I asked him for help, here is what he told me, hopefully
that will enlighten you ;)

504/7 > irb
irb(main):001:0> options={:value => 42}
=> {:value=>42}
irb(main):002:0> options.update( :answer => 42 )
=> {:value=>42, :answer=>42}
irb(main):003:0> options
=> {:value=>42, :answer=>42}
irb(main):004:0> options.merge( :wisdom => 42 )
=> {:value=>42, :answer=>42, :wisdom=>42}
irb(main):005:0> options
=> {:value=>42, :answer=>42}
irb(main):006:0> options.merge!( :wisdom => 42 )
=> {:value=>42, :answer=>42, :wisdom=>42}
irb(main):007:0> options
=> {:value=>42, :answer=>42, :wisdom=>42}

HTH
Robert
This topic is locked and can not be replied to.