Ruby: using .send inside a method behaves differently than calling it outside

I am trying to write a small snippet of my Rails application that checks for any tags for an object.

I have the following code:

def any_tags_present?(obj,*tags)
  tags ||= %w(person city country other)
  tags.any? { |tag| obj.send("#{tag}_list").present? }
end

      

running tags.any? { |tag| obj.send("#{tag}_list").present? }

will return true if I call it directly:

obj = Article.first
tags ||= %w(person city country other)
tags.any? { |tag| obj.send("#{tag}_list").present? }

=> true

      

but if i call it with any_tags_present?(Article.first)

i get false:

obj = Article.first
any_tags_present?(obj)

=> false

      

What gives?

+3


source to share


2 answers


You can something like

def any_tags_present?(obj, tags=nil)
  tags ||= %w(person city country other)
  tags.any? { |tag| obj.send("#{tag}_list").present? }
end

obj = Article.first
any_tags_present?(obj)

      



So, if you don't pass tags, then it gets initialized %w(person city country other)

+2


source


The problem is in the line tags ||= %w(person city country other)

. It doesn't receive (re) because it tags

will be empty Array

( []

), not nil

. Possible solutions simply accept a default argument nil

and pass in Array

or check if it is tags

empty.



+1


source







All Articles