Ruby: Object.to_a replacement

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

    It seems only Object.to_a is deprecated, removing a default to_a and forcing each class to define its own (e.g., Hash.to_a).

    self.to_a       #=> -:1: warning: default `to_a' will be obsolete
    "hello".to_a    #=> ["hello"]
    Time.new.to_a   #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, "CDT"]
    
    h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300  }
    h.to_a   #=> [["a", 100], ["c", 300], ["d", 400]]
    

    If your argument is an instance of Object, try:

    Hash.new(obj).to_a
    

    @Daniel [comment to Ollivier]: The point is that I don't know what the argument is. If it is an array already, I want to leave it, otherwise create a one-element array.

    If that's the case, try:

    obj = [obj] if !obj.is_a?(Array)
    

提交回复
热议问题