Search code examples
rubyenumerableruby-2.0

How do I limit loading of a particular Ruby module based on the version of Ruby


Lazy evaluation of enumerables has been included in Ruby 2.0: http://railsware.com/blog/2012/03/13/ruby-2-0-enumerablelazy/

I would like to include this notation (.lazy) in an application I'm writing but for people running any version of Ruby. However, if that person is running Ruby 2.0, I'd like to just let the native implementation take over.

Here's an project I'd probably use as a template: https://github.com/yhara/enumerable-lazy/blob/master/lib/enumerable/lazy.rb

How would I only load this module if the active version of Ruby is < 2.0?


Solution

  • Note that yhara's version is obsolete. You should use the one in my backports gem. It passes MRI's test for lazy:

    require 'backports/2.0.0/enumerable/lazy'
    (1..42).lazy... # => works in all Rubies
    

    Simply use a condition like Enumerable.method_defined?(:lazy) to know if you should define it or not (like I do in backports)