简体   繁体   中英

How can I make a method similar to Array() in Ruby (no dot syntax)?

In Ruby, you can use Array() to wrap an element in an empty array if it wasn't already an array:

Array(2) => [2]
Array([2, 3]) => [2, 3]

How would I define a method like on my own custom class? Like Foo() ? I'm having a hard time searching for it on the internet because I don't know exactly what's going on here.

Array() is the private method defined in Kernel module. So if you want your custom Foo() method that works in similar way, you could do:

module Kernel

  private

  def Foo(*args)
    # code
  end
end

You could also define this method in Object class, since Kernel is mixed-in to Object , there would be no difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM