...如在这个例子中:
helloworld.rb:1: syntax error, unexpected '=', expecting $end :helloworld = "hello ".concat("world")
我想如果我使用concat我正在修改字符串"hello"并向其添加"world",然后最终将结果字符串 - "hello world" - 分配给等号左侧的:helloworld符号.我认为那是合法的,就像我写的那样:
:helloworld = "hello world"
哦,等等,这也行不通.(划痕头).
Ruby符号不能赋值给它们,因为它们代表规范值.如果要从字符串构建符号,可以使用"hello".concat("world").to_sym.
试试这个:
:"hello world"
来自没有像他们这样的语言的符号令人困惑.你不能分配符号,这不是他们的目的.
以下是一些可能有助于解释它的示例.
5.times do |i| # a new string is created in each iteration of the loop puts "my string".object_id # there is only ever one symbol for each possible value # so a new object is not created during each iteration puts :my_symbol.object_id # this often makes a difference when you're using them for things like hash keys #some_method(:name => 'bob') #some_method('name' => 'bob') end
另一个很大的区别是符号比较只是一个指针比较.