tags:

views:

25

answers:

2

How simplify this part of code:

def value_format(value)
  if value.respond_to? :to_actor
    value.to_actor
  elsif value.respond_to? :to_subject
    value.to_subject
  elsif value.respond_to? :to_json
    value.to_json
  elsif value.respond_to? :to_hash
    value.to_hash
  else
    value.inspect
  end
end

Maybe is better answer than my solution:

def value_format(value)
  methods = [:to_actor, :to_subject, :to_json, :to_hash, :inspect]
  value.send(methods.find_all { |m| m if value.respond_to? m }.first)
end
+3  A: 

Your solution looks fine, but you might as well use find instead of find_all:

METHODS = [:to_actor, :to_subject, :to_json, :to_hash, :inspect]
def value_format(value)
  value.send(METHODS.find { |m| value.respond_to? m })
end

Using a constant has the advantage of not creating a new array every time value_format is ran.

Marc-André Lafortune
+1  A: 

Seems there's a pretty simple optimization to your solution:

def value_format(value)
  methods = [:to_actor, :to_subject, :to_json, :to_hash]
  value.send(methods.find(:inspect) { |m| value.respond_to? m })
end
Aidan Cully
He he, same idea, same time. Note that `find`'s argument has to be a `Proc` or `lambda`.
Marc-André Lafortune
@Marc-André Lafortune: Your answer was slightly earlier. Also, I didn't realize that about the argument to `find`... I'd consider your version better.
Aidan Cully