Pregunta

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
=> ","
¿Fue útil?

Solución 2

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
 => "," 

Otros consejos

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
=> ","
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top