Ruby: Object.to_a replacement

后端 未结 7 1460
后悔当初
后悔当初 2020-12-25 12:03

I need to convert a passed in argument (single object or collection) to an Array. I don\'t know what the argument is. If it is an Array already, I want to leave it, otherwis

7条回答
  •  爱一瞬间的悲伤
    2020-12-25 12:33

    You can take the duck typing aproach if that suits the problem better, make a list of all the methods you need, and check if the object already have them, if not, make it an array:

    [:[], :each, :etc...].all? { |m| obj.respond_to? m } ? obj : [obj]
    

    The advantage is that you give the object a chance to implement it's own semantics for indexed access.

提交回复
热议问题