我正在尝试从数组中读取字符串并将其转换为不带引号""
的符号。例如,给定:
my_array = ["apples", "oranges", "pears"]
我希望变量my_first_fruit
返回:apples
。我试过了:
my_first_fruit = my_array[0].to_sym
但是,它出现了:
my_first_fruit = :"apples"
我似乎无法摆脱""
。如果我输入
my_first_fruit = "apples"
my_first_fruit.to_sym
然后返回:apples
。那是为什么?
答案 0 :(得分:3)
尝试使用String#to_sym
method:
"apples".to_sym # => :apples
my_array = ["apples", "oranges", "pears"].map(&:to_sym)
my_array[0] # => :apples
答案 1 :(得分:3)
总结:
问题是使用'.to_sym'转换带空格的字符串(即:“Johnny Appleseed”)时,转换后的符号将显示为:“Johnny Appleseed”。这是由于'Johnny'和'Appleseed'之间的空间 - 如果您只是转换“苹果”,“橙子”或“梨子”,则不会发生。
如果您不想要引号,请在字符串中使用下划线而不是空格。
例如:
my_array = ["apple juice", "oranges", "pears"]
my_array.collect! {|fruit| fruit.to_sym}
将产生:
my_array[0] = :"apple juice"
my_array[1] = :oranges