# Hash is not merged / recursive function

**URL:** <https://www.ruby-forum.com/t/hash-is-not-merged-recursive-function/156934>\
**Category:** Ruby\
**Created:** [January 5, 2009, 3:35pm UTC](https://www.ruby-forum.com/t/hash-is-not-merged-recursive-function/156934 "2009-01-05T15:35:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![shihan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ea666f/32.png) [@shihan](https://www.ruby-forum.com/u/shihan)\
**Post date:** [January 5, 2009, 3:35pm UTC](https://www.ruby-forum.com/t/hash-is-not-merged-recursive-function/156934/1 "2009-01-05T15:35:09Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![shihan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ea666f/32.png) [@shihan](https://www.ruby-forum.com/u/shihan)\
**Post date:** [January 5, 2009, 5:21pm UTC](https://www.ruby-forum.com/t/hash-is-not-merged-recursive-function/156934/2 "2009-01-05T17:21:37Z")

</div>

On Mon, Jan 5, 2009 at 3:35 PM, Dominik Krebs  
[removed\_email\_address@domain.invalid](mailto: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
