What does send () do in Ruby?

Can someone tell me that

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

eat and do?

+83
ruby
Jul 26 '10 at 17:22
source share
5 answers

send sends a message to the object instance and its ancestors in the class hierarchy until a method responds (because its name corresponds to the first argument).

Practically speaking, these lines are equivalent:

 1.send '+', 2 1.+(2) 1 + 2 

Note that send bypasses visibility checks, so you can also call private methods (useful for unit testing).




If there really is no variable before sending, this means that a global object is used:

 send :to_s # "main" send :class # Object 
+94
Jul 26 2018-10-18T00:
source share

send is a ruby โ€‹โ€‹method (without rails) that allows you to call another method by name.

From the documentation

  class Klass def hello(*args) "Hello " + args.join(' ') end end k = Klass.new k.send :hello, "gentle", "readers" #=> "Hello gentle readers" 

http://corelib.rubyonrails.org/classes/Object.html#M001077

+93
Jul 26 '10 at 17:29
source share

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

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

To assign attributes regularly, you need to

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

Or using the .send method:

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

But all this can be replaced by the following:

Assuming your Rails application needs to assign attributes to your car class with user input, you can do

 c = Car.new() params.each do |key, value| c.send("#{key}=", value) end 
+53
04 Oct '14 at 2:31
source share

Another example similar to Antonio Jha

if you need to read the attributes for an object.

For example, if you have an array of strings, if you try to iterate through them and call them on your object, this will not work.

 atts = ['name', 'description'] @project = Project.first atts.each do |a| puts @project.a end # => NoMethodError: undefined method `a' 

However, you can send strings for the object:

 atts = ['name', 'description'] @project = Project.first atts.each do |a| puts @project.send(a) end # => Vandalay Project # => A very important project 
+8
Feb 04 '17 at 16:39
source share

Another use case for views:

  <%= link_to send("first_part_of_path_{some_dynamic_parameters}_end_path", attr1, attr2), .... %> 

Allow. you must write a scalable view that works with all types of objects with:

  render 'your_view_path', object: "my_object" 
0
Dec 18 '17 at 10:33
source share



All Articles