changing the value of a hash

Discussion in 'Ruby' started by Jf Rejza, Nov 9, 2008.

  1. Jf Rejza

    Jf Rejza Guest

    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
     
    Jf Rejza, Nov 9, 2008
    #1
    1. Advertisements

  2. 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
     
    Brian Candler, Nov 9, 2008
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.