Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to write a little snippet for my Rails app that checks if any tags are present 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?

like image 630
DaniG2k Avatar asked May 16 '26 12:05

DaniG2k


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 by %w(person city country other)

like image 119
Kranthi Avatar answered May 19 '26 01:05

Kranthi


The problem is the line tags ||= %w(person city country other). It doesn't get (re)assigned, because tags will be an empty Array ([]) and not nil. Possible solutions are just taking an default argument of nil and passing in an Array or checking if tags is empty.

like image 20
britishtea Avatar answered May 19 '26 02:05

britishtea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!