如何检查RUBY_VERSION是否大于某个版本?

时间:2021-10-23 19:46:42

Before I split the RUBY_VERSION 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_VERSION字符串拆分为句点并将这些位转换为整数等之前,如果当前的RUBY_VERSION大于X.X.X,是否有更简单的方法可以从Ruby程序中检查?

3 个解决方案

#1


12  

Ruby's Gem library can do version number comparisons:

Ruby的Gem库可以进行版本号比较:

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.

有关详细信息,请参阅http://rubydoc.info/stdlib/rubygems/1.9.2/Gem/Version。

#2


0  

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

#3


0  

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"

#1


12  

Ruby's Gem library can do version number comparisons:

Ruby的Gem库可以进行版本号比较:

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.

有关详细信息,请参阅http://rubydoc.info/stdlib/rubygems/1.9.2/Gem/Version。

#2


0  

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

#3


0  

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"