在 Ruby 1.8 中支持 Ruby 1.9 的哈希语法 [英] Supporting Ruby 1.9's hash syntax in Ruby 1.8
问题描述
我正在使用 {key: 'value'}
语法为整个代码中的散列编写一个 Ruby gem.我的测试都在 1.9.x 中通过,但我(可以理解)在 1.8.7 中得到 syntax error, unexpected ':', expecting ')'
.
I'm writing a Ruby gem using the {key: 'value'}
syntax for hashes throughout my code. My tests all pass in 1.9.x, but I (understandably) get syntax error, unexpected ':', expecting ')'
in 1.8.7.
是否有支持 1.8.x 的最佳实践?我是否需要使用我们的老朋友 =>
重写代码,或者有更好的策略吗?
Is there a best practice for supporting the 1.8.x? Do I need to rewrite the code using our old friend =>
, or is there a better strategy?
推荐答案
我觉得你运气不好,如果你想支持 1.8 那么你必须使用 =>
.像往常一样,我会提到在 1.9 的某些情况下必须使用 =>
:
I think you're out of luck, if you want to support 1.8 then you have to use =>
. As usual, I will mention that you must use =>
in certain cases in 1.9:
- 如果键不是符号.请记住,任何对象(符号、字符串、类、浮点数等)都可以作为 Ruby Hash 中的键.
- 如果您需要引用的符号:
:'this.that'
. - 如果您将 MongoDB 用于几乎任何事情,您将使用诸如
:$set => 之类的东西.hash
但$set: hash
是一个语法错误.
- If the key is not a symbol. Remember that any object (symbols, strings, classes, floats, ...) can be a key in a Ruby Hash.
- If you need a symbol that you'd quote:
:'this.that'
. - If you use MongoDB for pretty much anything you'll be using things like
:$set => hash
but$set: hash
is a syntax error.
回到我们定期安排的节目.
Back to our regularly scheduled programming.
为什么我说你不走运?Hash 文字语法(两者)在解析器中是硬连接的,我认为从 gem 修补解析器不会有太多运气.Ruby 1.8.7 的 parse.y
有话要说:
Why do I say that you're out of luck? The Hash literal syntaxes (both of them) are hard-wired in the parser and I don't think you're going to have much luck patching the parser from your gem. Ruby 1.8.7's parse.y
has this to say:
assoc : arg_value tASSOC arg_value
{
$$ = list_append(NEW_LIST($1), $3);
}
;
和 tASSOC
是 =>
所以散列文字是硬连线的以使用 =>
.1.9.3's 是这样说的:
and tASSOC
is =>
so hash literals are hard-wired to use =>
. 1.9.3's says this:
assoc : arg_value tASSOC arg_value
{
/*%%%*/
$$ = list_append(NEW_LIST($1), $3);
/*%
$$ = dispatch2(assoc_new, $1, $3);
%*/
}
| tLABEL arg_value
{
/*%%%*/
$$ = list_append(NEW_LIST(NEW_LIT(ID2SYM($1))), $2);
/*%
$$ = dispatch2(assoc_new, $1, $2);
%*/
}
;
我们再次使用粗箭头语法(arg_value tASSOC arg_value
)和 JavaScript 样式(tLABEL arg_value
);AFAIK,tLABEL
也是限制符号种类的来源(没有 :$set
,没有 :'this.that'
,...) 可以与 JavaScript 风格的语法一起使用.当前主干 parse.y
匹配 1.9.3 的哈希文字.
We have the fat-arrow syntax again (arg_value tASSOC arg_value
) and the JavaScript style (tLABEL arg_value
); AFAIK, tLABEL
is also the source of the restrictions on what sorts of symbols (no :$set
, no :'this.that'
, ...) can be used with the JavaScript-style syntax. The current trunk parse.y
matches 1.9.3 for Hash literals.
所以 Hash 文字语法被硬连接到解析器中,如果你想支持 1.8,你就会被粗箭头所困.
So the Hash literal syntax is hard-wired into the parser and you're stuck with fat arrows if you want to support 1.8.
这篇关于在 Ruby 1.8 中支持 Ruby 1.9 的哈希语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!