Ruby on rails 字符串插值不适用于Ruby Herdeoc常量
我有一个很长的常量定义,需要插值(实际的定义要长得多): 现在,为了使其更具可读性,我尝试使用heredocs创建多行字符串:Ruby on rails 字符串插值不适用于Ruby Herdeoc常量,ruby-on-rails,ruby,interpolation,heredoc,Ruby On Rails,Ruby,Interpolation,Heredoc,我有一个很长的常量定义,需要插值(实际的定义要长得多): 现在,为了使其更具可读性,我尝试使用heredocs创建多行字符串: const = <<-EOT.constantize This::Is::ThePath:: To::MyModule::#{a_variable} EOT const=: const = <<-EOT.constantize This::Is::ThePath:: To::MyModule::#{a_variable} EOT
const = <<-EOT.constantize
This::Is::ThePath::
To::MyModule::#{a_variable}
EOT
const=:
const = <<-EOT.constantize
This::Is::ThePath::
To::MyModule::#{a_variable}
EOT
对于许多行:
conts = <<-EOF
=> ActionDispatch::
=> Integration::
=> Session
=> EOF
=> "ActionDispatch::\nIntegration::\nSession\n"
conts=集成::
=>会话
=>EOF
=>“ActionDispatch::\n整合::\n会话\n”
修复它:
conts = <<-EOF.gsub(/\n/, '').constantize
=> ActionDispatch::
=> Integration::
=> Session
=> EOF
=> ActionDispatch::Integration::Session
conts=集成::
=>会话
=>EOF
=>ActionDispatch::Integration::Session
从此文档中删除所有空格和换行符
在调用#constantize之前,需要从插入的here文档中删除所有空格、制表符和换行符。以下自包含示例将起作用:
require 'active_support/inflector'
module This
module Is
module ThePath
module To
module MyModule
module Foo
end
end
end
end
end
end
a_variable = 'Foo'
const = <<EOT.gsub(/\s+/, '').constantize
This::Is::ThePath::
To::MyModule::#{a_variable}
EOT
#=> This::Is::ThePath::To::MyModule::Foo
需要“主动支持/拐点”
模块本
模块是
模块路径
模块到
模块MyModule
模块Foo
结束
结束
结束
结束
结束
结束
a_变量='Foo'
const=与我从错误消息中看到的没有任何区别吗?不只是最后的换行符,两行之间的换行符和前导空格也需要删除。对于多行使用。gsub(/\n/,“”)
而不是chomp
conts = <<-EOF
=> ActionDispatch::
=> Integration::
=> Session
=> EOF
=> "ActionDispatch::\nIntegration::\nSession\n"
conts = <<-EOF.gsub(/\n/, '').constantize
=> ActionDispatch::
=> Integration::
=> Session
=> EOF
=> ActionDispatch::Integration::Session
require 'active_support/inflector'
module This
module Is
module ThePath
module To
module MyModule
module Foo
end
end
end
end
end
end
a_variable = 'Foo'
const = <<EOT.gsub(/\s+/, '').constantize
This::Is::ThePath::
To::MyModule::#{a_variable}
EOT
#=> This::Is::ThePath::To::MyModule::Foo