开发者

How to check if the RUBY_VERSION is greater than a certain version?

开发者 https://www.devze.com 2023-02-09 17:36 出处:网络
Before I split the RUBY_VER开发者_运维知识库SION string on a period and convert the bits into integers and so on, is there a simpler way to check from a Ruby program if the current RUBY_VERSION is gre

Before I split the RUBY_VER开发者_运维知识库SION string on a period and convert the bits into integers and so on, is there a simpler way to check from a Ruby program if the current RUBY_VERSION is greater than X.X.X?


Ruby's Gem library can do version number comparisons:

require 'rubygems' # not needed with Ruby 1.9+

ver1 = Gem::Version.new('1.8.7') # => #<Gem::Version "1.8.7">
ver2 = Gem::Version.new('1.9.2') # => #<Gem::Version "1.9.2">
ver1 <=> ver2 # => -1

See http://rubydoc.info/stdlib/rubygems/1.9.2/Gem/Version for more info.


User diedthreetimes' answer is much simpler, and the method I use... except it uses string comparison, which is not best practice for version numbers. Better to use numeric array comparison like this:

version = RUBY_VERSION.split('.').map { |x| x.to_i }
if (version <=> [1, 8, 7]) >= 1
  ...
end


Instead of comparing version number, then perhaps check if the method exist, like this:

text = "hello world"
find = "hello "
if String.method_defined? :delete_prefix!
    # Introduced with Ruby 2.5.0, 2017-10-10, https://blog.jetbrains.com/ruby/2017/10/10-new-features-in-ruby-2-5/
    text.delete_prefix!(find)
else
    text.sub!(/\A#{Regexp.escape(find)}/, '')
end
p text # => "world"
0

精彩评论

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