我的字符串就像这个"SHN::test::cg1","RDC::TEST::CONFIG 1"
,但是将它存储在变量
new_string="SHN::test::cg1","RDC::TEST::CONFIG 1","MDC::test::cg1"
我插入像这样的“#{new_string}”。值类似于
""SHN::test::cg1","RDC::TEST::CONFIG 1""
更新1: 这是我需要使用那个
的场景$redis.subscribe("RDC::TEST::CONFIG 1","SHN::test::cg1") do |on|
#hardcoded values inside braces
end
但我需要传递一个变量来形成像上面那样的字符串(在大括号内),我试过
$redis.subscribe("#{new_string}") do |on|
#interpolated value inside braces
end
更新2:回答 我只需要将new_string作为数组传递,不需要转换为字符串这是我的场景
的答案$redis.subscribe(new_string) do |on|
#interpolated value inside braces
end
提前致谢....
答案 0 :(得分:1)
你的new_string
实际上是一个数组,而不是一个字符串!原因是因为你实际上有三个用逗号分隔的字符串,所以Ruby将它解析为一个字符串数组:
irb> new_string="SHN::test::cg1","RDC::TEST::CONFIG 1","MDC::test::cg1"
=> ["SHN::test::cg1", "RDC::TEST::CONFIG 1", "MDC::test::cg1"]
当你将它插入到一个新字符串中时,Ruby会在数组上调用.to_s
,这会(根据你的Ruby版本)产生你所看到的内容:
irb> ["SHN::test::cg1","RDC::TEST::CONFIG 1","MDC::test::cg1"].to_s
=> "[\"SHN::test::cg1\", \"RDC::TEST::CONFIG 1\", \"MDC::test::cg1\"]"
irb> puts ["SHN::test::cg1","RDC::TEST::CONFIG 1","MDC::test::cg1"].to_s
["SHN::test::cg1", "RDC::TEST::CONFIG 1", "MDC::test::cg1"]
要解决此问题,只需将new_string
设为实际字符串(通过修复定义中的语法)。或者,自己将数组转换为字符串,例如:
irb> "#{new_string.join('')}"
=> "SHN::test::cg1RDC::TEST::CONFIG 1MDC::test::cg1"