# Changing the value of a hash

**URL:** <https://www.ruby-forum.com/t/changing-the-value-of-a-hash/152921>\
**Category:** Ruby\
**Created:** [November 9, 2008, 9:22pm UTC](https://www.ruby-forum.com/t/changing-the-value-of-a-hash/152921 "2008-11-09T21:22:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![manchoman](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/91b2a8/32.png) [@manchoman](https://www.ruby-forum.com/u/manchoman)\
**Post date:** [November 9, 2008, 9:22pm UTC](https://www.ruby-forum.com/t/changing-the-value-of-a-hash/152921/1 "2008-11-09T21:22:26Z")

</div>

Hi

I have an active record object collection. I want to change the value of  
the key called “mail”.

@users.collect {|s|s.attributes.x\_method { if key == mail then replace @  
something else (ex: value.gsub(/@/," (at) ") }}.to\_json

How can I achieve my gold?

thanks  
jf

---

<div class="post-metadata">

**Author:** ![manchoman](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/91b2a8/32.png) [@manchoman](https://www.ruby-forum.com/u/manchoman)\
**Post date:** [November 9, 2008, 11:14pm UTC](https://www.ruby-forum.com/t/changing-the-value-of-a-hash/152921/2 "2008-11-09T23:14:51Z")

</div>

Jf Rejza wrote:

> I want to change the value of  
> the key called “mail”.

I’d probably just write something simple like:

h = s.attributes  
h[‘mail’].gsub!(’@’,’ (at) ') if h[‘mail’]

If you really want to iterate, then

h = s.attributes  
h.each { |k,v| h[k] = v.gsub(’@’,’ (at) ') if k==‘mail’ && v }

And if you want to write it as a one-liner, look at inject or merge. If  
you know there’s always a mail attribute, then:

s.attributes.merge( ‘mail’ =\> s.attributes[‘mail’].gsub(’@’,’ (at) ’  
).to\_json
