开发者

How do you extend collection(?) to include second, third, etc. functions in Rails?

开发者 https://www.devze.com 2023-03-14 06:24 出处:网络
开发者_StackOverflow中文版Pretty self explanatory. I use array_name.first to get the first element. How do you extend it to get second, third, random, etc?
开发者_StackOverflow中文版

Pretty self explanatory.

I use array_name.first to get the first element. How do you extend it to get second, third, random, etc?

Thanks.


In Ruby you can just reopen any existing class and add your own functions.

In rails, you already have those methods defined in activesupport

See the source at github: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/array/access.rb


I discovered it is already there, in Ruby 1.9.2 at least.

If it weren't there, I would create a file in config/initializers called array_helper.rb (or whatever) and add the following code:

class Array
  def second
    self[1]
  end
end

Why? Because all classes in Ruby are open and you can extend anything you want.

Here's some tricks to know:

When working in the console, if you want to test the file, be sure to use rails console and not irb. Also, do reload! after creating or updating the above file. Finally, all objects must be recreated to use the new code after reload!.

0

精彩评论

暂无评论...
验证码 换一张
取 消