ruby - Refactoring respond_to? call in if-elsif-else condition -


I have the following method and want to make it more readable:

  def value_format (Value) if value.respond_to? : To_actor value.to_actor elsif value. : To_subject value.to_subject elsif value. : To_json value.to_json elsif value. : To_hash value.to_hash Other values Inspect end end  

This is my solution What do you think? Def value_format (value) methods = [: to_actor ,: to_subject ,: to_json, to_hash,] inspection value.send (methods.find_all {| m | m if value.respond_to? M } .first) end

Your solution looks ok, but you You can use Find instead of find_all :

  METHODS = [: to_actor, to_subject ,: to_json, to_hash,:  < / Pre> 

The advantage of not making a new array to use a constant is to run value_format at all times.


Comments