Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > dynamic assignment of iterator name

Reply
Thread Tools

dynamic assignment of iterator name

 
 
Leah Cunningham
Guest
Posts: n/a
 
      03-05-2006
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/.


 
Reply With Quote
 
 
 
 
Wilson Bilkovich
Guest
Posts: n/a
 
      03-05-2006
On 3/5/06, Leah Cunningham <(E-Mail Removed)> 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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
List iterator assignment fails, assert iterator not dereferencable David Bilsby C++ 5 10-09-2007 02:05 PM
What makes an iterator an iterator? Steven D'Aprano Python 28 04-20-2007 03:34 AM
Difference between Java iterator and iterator in Gang of Four Hendrik Maryns Java 18 12-22-2005 05:14 AM
How to convert from std::list<T*>::iterator to std::list<const T*>::iterator? PengYu.UT@gmail.com C++ 6 10-30-2005 03:31 AM
Iterator doubts, Decision on Iterator usage greg C++ 6 07-17-2003 01:26 PM



Advertisments