带有各种字符的符号

时间:2017-08-22 09:51:21

标签: ruby symbols

我想将以下字符串转换成符号:

  • 'Architects & Engineers'
  • 'Catering & Hotels'

他们有'&''/'等字符。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:5)

'Architects & Engineers'.to_sym == :'Architects & Engineers'
#⇒ true

['Architects & Engineers'.to_sym, :'Architects & Engineers'].map(&:to_s)
#⇒ ["Architects & Engineers", "Architects & Engineers"]

答案 1 :(得分:0)

您可以使用classy_enum gem https://github.com/AgilionApps/classy_enum

class YourEnum < ClassyEnum::Base
end

class YourEnum::ArchitectAndEngineer < YourEnum
  def to_s
    "Architects & Engineers"
  end
end

class YourEnum::DocterOrEngineer < YourEnum
  def to_s
    "Doctor/Engineer"
  end
end

然后你可以像

一样使用它
YourEnum.map(&:to_s) # ["Architects & Engineers", "Doctor/Engineer"]

您可以找到类似

的枚举
YourEnum.find("Architects & Engineers") #<YourEnum::ArchitectAndEngineer:0x007f96ccb16628>

答案 2 :(得分:0)

另一种方式:

:"Architects & Engineers"     # => :"Architects & Engineers"
:"Architects & Engineers" == "Architects & Engineers".to_sym # => true