# String as method call?

**URL:** <https://www.ruby-forum.com/t/string-as-method-call/172537>\
**Category:** Rails\
**Created:** [July 23, 2009, 12:25am UTC](https://www.ruby-forum.com/t/string-as-method-call/172537 "2009-07-23T00:25:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![elliottg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/b77776/32.png) [@elliottg](https://www.ruby-forum.com/u/elliottg)\
**Post date:** [July 23, 2009, 12:25am UTC](https://www.ruby-forum.com/t/string-as-method-call/172537/1 "2009-07-23T00:25:39Z")

</div>

Should be simple but I can’t eval a string as a method call. I have  
poked around online a fair amount to get to the bottom of this mundane  
task, with no results.

I have a hash “fields” that contains a series of AR field names and an  
object called “news” which is an AR object with that has the field  
names that are coming in from the hash. I just want to assign the hash  
values to the same field value from the news object.

I have tried all these variations but with no luck. Mostly just blows  
up with syntax errors.

fields.each\_pair {|key, value| news.eval(“key”) = value }

fields.each\_pair {|key, value| news."#{key}" = value }

fields.each\_pair {|key, value| “#{news.key}” = value }

fields.each\_pair {|key, value| “news.#{key} = #{value}” }

fields.each\_pair {|key, value| news.send key = value }

How do I do this?

Thanks, Elliott

---

<div class="post-metadata">

**Author:** ![elliottg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/b77776/32.png) [@elliottg](https://www.ruby-forum.com/u/elliottg)\
**Post date:** [July 23, 2009, 12:53am UTC](https://www.ruby-forum.com/t/string-as-method-call/172537/2 "2009-07-23T00:53:43Z")

</div>

On Jul 22, 2009, at 6:24 PM, elliottg wrote:

> up with syntax errors.  
> fields.each\_pair {|key, value| news.send key = value }
> 
> How do I do this?
> 
> Thanks, Elliott

news.update\_attributes(fields)

but the syntax you were struggling to find is probably:

fields.each\_pair {|key,value| news.send(“#{key}=”, value) }

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![elliottg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/b77776/32.png) [@elliottg](https://www.ruby-forum.com/u/elliottg)\
**Post date:** [July 23, 2009, 4:04pm UTC](https://www.ruby-forum.com/t/string-as-method-call/172537/3 "2009-07-23T16:04:21Z")

</div>

Thanks Rob.

The send syntax worked perfectly! In this case I don’t think  
news.update\_attributes(fields) will work, because fields hash values  
conflicts with my validations, but It helped me to think a bit  
differently in general.

Elliott

On Jul 22, 6:52 pm, Rob B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
