Ruby: Object.to_a replacement

后端 未结 7 1488
后悔当初
后悔当初 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:26

    Wow, someone just necromanced a really old thread. :-O But since I don't see it included yet, I'll add one more way for completeness' sake:

    arg = [*arg]
    

    This will splat the argument if it already is an array (thus removing one level of nesting) or create a one-argument array otherwise:

    arg = [1,2,3]
    [*arg] #=> [1, 2, 3]
    arg = 1
    [*arg] #=> [1]
    

提交回复
热议问题