swa*_*esh 13 ruby hash symbols
我正在为电影名称存储创建一个Ruby哈希.
当哈希的键是包含空格的字符串时,它可以正常工作.
如:
movies = {"Avatar" => 5, "Lord of the rings" => 4, "Godfather" => 4}
现在我试图用符号替换字符串的使用:
movies = {Avatar: 5, Lord of the rings: 4, Godfather: 4}
显然这不起作用.
Ruby如何处理符号命名中的空格?
old*_*god 17
亲自尝试一下
"Lord of the rings".to_sym
#=> :"Lord of the rings"
Run Code Online (Sandbox Code Playgroud)
我不确定为什么你想在键值中想要空格时使用符号,但是你可以这样做.你只是不能使用<symbol>: <value>
语法...
{:Avatar => 5, :"Lord of the rings" => 4, :Godfather => 4}
Run Code Online (Sandbox Code Playgroud)