What does send() do in Ruby?

后端 未结 6 1023
野性不改
野性不改 2020-11-28 01:49

Can someone please tell me what

send(\"#{Model.find...}\")

is and does?

6条回答
  •  悲&欢浪女
    2020-11-28 02:28

    One of the most useful feature I think with .send method is that it can dynamically call on method. This can save you a lot of typing. One of the most popular use of .send method is to assign attributes dynamically. For example:

    class Car
      attr_accessor :make, :model, :year
    end  
    

    To assign attributes regularly one would need to

    c = Car.new
    c.make="Honda"
    c.model="CRV"
    c.year="2014"
    

    Or using .send method:

    c.send("make=", "Honda")
    c.send("model=", "CRV")
    c.send("year=","2014")
    

    But it can all be replaced with the following:

    Assuming your Rails app needs to assign attributes to your car class from user input, you can do

    c = Car.new()
    params.each do |key, value|
      c.send("#{key}=", value)
    end
    

提交回复
热议问题