문제

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
=> ","
도움이 되었습니까?

해결책 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
 => "," 

다른 팁

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
=> ","
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top