0

See the following code:

1  str1 = gets
2  str2 = "Hello"
3  puts str1
4  puts str1.to_sym().object_id()
5  puts str2.to_sym().object_id()
6  puts :"Hello".object_id()

In Line 1, I input "Hello" from stdin and save this string to var str1. In Line 2, I save a string "Hello" to var str2. Now str1 and str2 contains same string, although they are different string object, and their values are same. According to rule of symbol, I except I can get game symbol of "Hello" from str1 and str2. But output is:

Hello
213748
213548
213548

It looks that str1 has different symbol from str2. How can I get symbol of "Hello" from str1?

I ask this question because I'm facing a problem that, I need to input some words from stdin, then use these words as key to build a hash table. As hash table should use symbol as key to avoid memory waste, I need to get symbol of input words.

4

2 回答 2

6

现在 str1 和 str2 包含相同的字符串,尽管它们是不同的字符串对象,并且它们的值相同

你的假设是不正确的。

符号不同,因为字符串不同。字符串 fromgets以换行符结尾。您可以通过检查 的值向自己证明这一点:"Hello\n".object_id

用于strip删除尾随换行符,两个字符串将相同,并且都将to_sym使用相同的符号:

puts str1.strip.to_sym.object_id
于 2013-08-22T02:28:57.077 回答
3

@meagar 关于换行符是正确的,但是您也可以使用chomp

为了演示这里是一个来自 irb 的示例会话:

2.0.0p247 :001 > without_chomp = gets
Hello
 => "Hello\n"
2.0.0p247 :002 > with_chomp = gets.chomp
Hello
 => "Hello" 
2.0.0p247 :003 > with_chomp_and_to_sym = gets.chomp.to_sym
Hello
 => :Hello 
于 2013-08-22T02:44:48.420 回答