在 Ruby 中,'#{ }' 是一种字符串内插语法,用于将表达式的结果嵌入到字符串中。例如:

name = 'Alice'
puts 'Hello #{name}!'   # 输出 'Hello Alice!'

'$' 符号通常用于全局变量、实例变量或类变量的引用。例如:

$global_var = 'hello'
class MyClass
  def say_hello
    puts $global_var
  end
end

obj = MyClass.new
obj.say_hello   # 输出 'hello'

在正则表达式中,'$' 符号用于匹配字符串末尾。例如:

str = 'hello world'
if str =~ /world$/
  puts 'Match found!'
end

其中 '$' 表示字符串末尾,如果正则表达式匹配到字符串末尾的'world',则输出'Match found!'。

Ruby 中 #{} 和 $ 的含义及用法

原文地址: https://www.cveoy.top/t/topic/mXCt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录