是否有DRYer方法将名为:comma
的符号转换为实际逗号(,
)?
目前的做法:
> delimiters = {:comma =>",", :semicolon=>";"}
=> {:comma=>",", :semicolon=>";"}
> chosen = :comma
> delimiters[chosen]
=> ","
理想:
> x = :comma
=> :comma
> x.from_sym # not valid, obviously
=> ","
答案 0 :(得分:4)
你可以这样做,但我不推荐它。解决方案是对Symbol类进行猴子修补,以便为您提供所需的功能。 这不是一个好的想法
class Symbol
DELIMITERS = {comma: ",", semicolon: ";"}
def from_sym
DELIMITERS[self]
end
end
irb(main):015:0> chos = :comma
=> :comma
irb(main):016:0> chos.from_sym
=> ","
答案 1 :(得分:1)
没有。符号等于其字符串表示,但没有其他隐藏的含义或转换。这与'2' != 2 != :'2'
完全相同,尽管在这种情况下您可以使用to_i
应用某些投射。
您实际上可以使用逗号的符号表示,但我不确定它是否使代码更具可读性。
2.0.0-p353 :011 > var = :','
=> :","
2.0.0-p353 :012 > var.class
=> Symbol
2.0.0-p353 :013 > var.to_s
=> ","