Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 符号到字符串的问题_Ruby_String_Symbols - Fatal编程技术网

Ruby 符号到字符串的问题

Ruby 符号到字符串的问题,ruby,string,symbols,Ruby,String,Symbols,以下代码失败 world = :world result = 'hello' + world puts result #=> can't convert Symbol into String 下面的代码有效 world = :world result = "hello #{world}" puts result #=> hello world 为什么? 使用ruby 1.8.7时,符号不是字符串,因此,如果不进行显式转换,就无法将其连接到字符串。试试这个: result = 'h

以下代码失败

world = :world
result = 'hello' + world
puts result #=> can't convert Symbol into String
下面的代码有效

world = :world
result = "hello #{world}"
puts result #=> hello world
为什么?

使用ruby 1.8.7

时,符号不是字符串,因此,如果不进行显式转换,就无法将其连接到字符串。试试这个:

result = 'hello ' + world.to_s
puts result

字符串插值是一种隐式调用。比如说:

result = "hello #{expr}"
大致相当于:

result = "hello " + expr.to_s

正如卡里姆79所说,符号不是字符串,但符号确实有
to_s
方法,因此插值是有效的;使用
+
进行串联的尝试无效,因为没有任何
+
实现可以理解左侧的字符串和右侧的符号。

如果
world
是一个数字,则会出现相同的行为

"hello" + 1 # Doesn't work in Ruby
"hello #{1}" # Works in Ruby
如果要向某个对象添加字符串,请在其上实现
to_str

irb(main):001:0> o = Object.new
=> #<Object:0x134bae0>
irb(main):002:0> "hello" + o
TypeError: can't convert Object into String
        from (irb):2:in `+'
        from (irb):2
        from C:/Ruby19/bin/irb:12:in `<main>'
irb(main):003:0> def o.to_str() "object" end
=> nil
irb(main):004:0> "hello" + o
=> "helloobject"
irb(main):001:0>o=Object.new
=> #
irb(主):002:0>“你好”+o
TypeError:无法将对象转换为字符串
from(irb):2:in`+'
来自(irb):2
来自C:/Ruby19/bin/irb:12:in`'
irb(主):003:0>def o.to_str()“对象”结束
=>零
irb(主):004:0>“你好”+o
=>“helloobject”

to_s
意味着“你可以把我变成一个字符串”,而
to_str
意味着“无论出于什么目的,我都是一个字符串”。

作为旁注,你可以自己定义方法:)


您还可以做一些有趣的事情,比如对数组中的一组不同对象进行隐式字符串调用
[:hello,“world”]。join(“”)和
result=“hello”+expr
相当于
result=“hello”+expr.to_str
@Mattias:除了字符串的
+
操作符检查
expr
是否有
to_str
方法,因此您会得到一个类型错误,而不是NoMethodError.yesp。我通常会用“强制”和“转换”来描述这两种行为,但不幸的是,“强制”一词在Ruby中的含义已经有所不同,错误消息在
到\u str
的上下文中谈到了转换。所以,在Ruby中,
到str
(和
到int
到ary
到float
)是转换,我简直想不出一个好名字来形容
到s
到I
到a
到f
)@Joerg:谢谢!由于您的反馈,我已经从我的答案中删除了“convert”一词。JavaScript是动态类型和松散类型,后者意味着某些转换会发生在您身上。(因此出现了旧的
'1'+1=='11'
问题。)Ruby是动态类型但强类型的,这意味着(除了少数例外)您需要显式执行转换……但当然,这甚至不适用于OP的字符串+符号问题。您需要使用monkeypatch String#+来执行类型转换。
ruby-1.9.2-p0 > class Symbol
ruby-1.9.2-p0 ?>  def +(arg)
ruby-1.9.2-p0 ?>    [to_s, arg].join(" ")
ruby-1.9.2-p0 ?>    end
ruby-1.9.2-p0 ?>  end
 => nil 
ruby-1.9.2-p0 > :hello + "world"
 => "hello world"