在特定 ruby 版本下强制 .rb 文件 运行

Force .rb file running under specific ruby versions

我在 .rb 文件中写了一个 ruby 脚本。它使用最新的 Ruby 功能(版本 2.7)。有没有办法强制这个.rb文件只能在特定的Ruby版本范围内执行?例如,.rb 文件的第一行可以是:

#! ruby 2.7+
# This .rb file can only be run with Ruby version 2.7 or above

天真,

unless RUBY_VERSION[0, 3] == "2.7"
  puts "You need 2.7")
  exit
end 

使用 gem semantic 处理解析当前 Ruby 版本:

require 'semantic'

# Require >= 2.7 < 3
exit unless Semantic::Version.new(RUBY_VERSION).satisfies?('~> 2.7')

# Require >= 2.7, including 3 and above
exit unless Semantic::Version.new(RUBY_VERSION).satisfies?('>= 2.7')

这需要您在应用中使用捆绑器和 Gemfile。

其他比较器列在the source code for the gem:

if ['<', '>', '<=', '>='].include?(comparator)
  satisfies_comparator? comparator, pad_version_string(other_version_string)
elsif comparator == '~>'
  pessimistic_match? other_version_string
else
  tilde_matches? other_version_string
end

这将允许您微调您的版本要求。