Is there a easy way to wraps an element in an array only it was not a array?

Basically, just a wrapper like this:

class Array(T)
  def self.wrap(e)
    if e.is_a? Array
      e
    else
      arr = Array(typeof(e)).new
      arr << e
      arr
    end
  end
end

p Array.wrap(100)   # => [100]
p Array.wrap([100]) # => [100]

For Ruby, it just y = Array(x), for Rails, y = Array.wrap(x).

I found it more useful when porting ruby code to crystal, thanks.

e.is_a?(Array) ? e : [e]

2 Likes

Feels like my original approach was so stupid …

do you consider accept following as a feature PR?

class Array(T)
  def self.wrap(e : T)
    e.is_a?(Array) ? e : [e]
  end
end

It is more simple when used as a method, e.g.

page.command("DOM.setFileInputFiles", files: Array.wrap(value))

I think that would require the type of e to be T, like: def self.wrap(e : T)

1 Like