dynamic assignment of iterator name

Discussion in 'Ruby' started by Leah Cunningham, Mar 5, 2006.

  1. I apologize if this is a foolish questions, but I am new to the language
    and having trouble finding an example of what I am looking to do (if
    it's possible.)

    I would like to know if there is a way to pass in the name of the
    iterator to use from a variable or similar. I am looking to do
    something like:

    params[:user].each_key do |attr|
    user.attr = params[:user][attr]
    end

    For now I can just use a giant case statement like this:

    params[:user].each_key do |attr|
    case attr
    when "givenName"
    user.givenName = params[:user][attr]
    when "sn"
    user.sn = params[:user][attr]
    when "mail"
    user.mail = params[:user][attr]
    when "o"
    user.o = params[:user][attr]
    end
    end

    But it would be nice to know if there is a cleaner way to handle this.

    --
    Posted via http://www.ruby-forum.com/.
     
    Leah Cunningham, Mar 5, 2006
    #1
    1. Advertising

  2. On 3/5/06, Leah Cunningham <> wrote:
    > I apologize if this is a foolish questions, but I am new to the language
    > and having trouble finding an example of what I am looking to do (if
    > it's possible.)
    >
    > I would like to know if there is a way to pass in the name of the
    > iterator to use from a variable or similar. I am looking to do
    > something like:
    >
    > params[:user].each_key do |attr|
    > user.attr =3D params[:user][attr]
    > end
    >
    > For now I can just use a giant case statement like this:
    >
    > params[:user].each_key do |attr|
    > case attr
    > when "givenName"
    > user.givenName =3D params[:user][attr]
    > when "sn"
    > user.sn =3D params[:user][attr]
    > when "mail"
    > user.mail =3D params[:user][attr]
    > when "o"
    > user.o =3D params[:user][attr]
    > end
    > end
    >


    You can use "send" for this, and using the multi-variable block on
    'each' will save you a further step.

    params[:user].each do |key, value|
    user.send("#{key}=3D", value)
    end
     
    Wilson Bilkovich, Mar 5, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hendrik Maryns
    Replies:
    18
    Views:
    1,455
  2. greg
    Replies:
    6
    Views:
    475
    Dietmar Kuehl
    Jul 17, 2003
  3. Replies:
    6
    Views:
    682
    Jim Langston
    Oct 30, 2005
  4. Steven D'Aprano

    What makes an iterator an iterator?

    Steven D'Aprano, Apr 18, 2007, in forum: Python
    Replies:
    28
    Views:
    1,240
    Steven D'Aprano
    Apr 20, 2007
  5. David Bilsby
    Replies:
    5
    Views:
    2,078
    David Bilsby
    Oct 9, 2007
Loading...

Share This Page