Reputation: 26272
Is there a DRYer way to convert a symbol named :comma
to an actual comma (,
)?
Current approach:
> delimiters = {:comma =>",", :semicolon=>";"}
=> {:comma=>",", :semicolon=>";"}
> chosen = :comma
> delimiters[chosen]
=> ","
Ideal:
> x = :comma
=> :comma
> x.from_sym # not valid, obviously
=> ","
Upvotes: 1
Views: 122
Reputation: 1375
You can do this, but I wouldn't recommend it. The solution is to monkey-patch the Symbol class to give you the functionality you want. THIS IS NOT A GOOD IDEA
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
=> ","
Upvotes: 4
Reputation: 176562
No. A symbol is equal to its string representation, but there are no other hidden meanings or transformations. This is exactly like '2' != 2 != :'2'
, despite in this case you can apply some casting using to_i
.
You could actually use the symbol representation of a comma, but I'm not sure it makes the code more readable.
2.0.0-p353 :011 > var = :','
=> :","
2.0.0-p353 :012 > var.class
=> Symbol
2.0.0-p353 :013 > var.to_s
=> ","
Upvotes: 1