简体   繁体   中英

ruby dynamic method passing a value

How do I pass a value to a dynamic method name that's called on a rails model?

@model.send(dynamic_method_name.to_sym,123)

This gives the error:

 wrong number of arguments (1 for 0)

If I were to use the same method like this though:

 @model.post_id = 123

then it works.

So there is a "setter" method for the method post_id (and therefore the dynamic method name).

How do I pass a value to this setter when the method is dynamic?

thanks!

You need to add the "=" to your dynamic_method_name. In ruby, :post_id is the name of the getter, and :post_id= is the name of the setter. The .to_sym isn't strictly necessary so you can do this:

@model.send("#{dynamic_method_name}=", 123)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM