簡體   English   中英

字符串插值不適用於Ruby heredoc常量

[英]String interpolation not working for Ruby heredoc constant

我有一個很長的常量定義,需要插值(實際的更長):

const = "This::Is::ThePath::To::MyModule::#{a_variable}".constantize

現在,為了使其更具可讀性,我嘗試使用heredocs來創建多行字符串:

const = <<-EOT.constantize
  This::Is::ThePath::
  To::MyModule::#{a_variable}
EOT

但是當我執行它時,我得到一個NameError: wrong constant name 由於第一個例子正在工作,我認為它與字符串插值有關?

有關這出錯的問題嗎?

從Here-Document中刪除所有空格和換行符

在調用#constantize之前,您需要從插值的here-document中刪除所有空格,制表符和換行符。 以下自包含示例將起作用:

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

代替:

const = <<-EOT.constantize
  This::Is::ThePath::
  To::MyModule::#{a_variable}
EOT

采用:

const = <<-EOT.gsub(/\n/, '').constantize
  This::Is::ThePath::
  To::MyModule::#{a_variable}
EOT

這個方法創建字符串<<-EOF ... EOF\\n放在行尾,然后constantize無法正常工作。 刪除不需要的字符\\n, \\t, \\s和所有應該工作。

看看我的測試用例:

conts = <<-EOF.constantize
=> ActionDispatch::Integration::Session
=> EOF

#> NameError: wrong constant name "Session\n"

conts = <<-EOF.chomp.constantize
=> ActionDispatch::Integration::Session
=> EOF
#> ActionDispatch::Integration::Session

對於許多行:

conts = <<-EOF
=> ActionDispatch::
=> Integration::
=> Session
=> EOF
=> "ActionDispatch::\nIntegration::\nSession\n"

修理它:

conts = <<-EOF.gsub(/\n/, '').constantize
=> ActionDispatch::
=> Integration::
=> Session
=> EOF
=> ActionDispatch::Integration::Session

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM