jbk
jbk

Reputation: 2202

Symbols with various characters

I would like to turn strings like the following into symbols:

They have characters like '&', '/'.

How can I achieve this?

Upvotes: 0

Views: 49

Answers (3)

steenslag
steenslag

Reputation: 80065

Another way:

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

Upvotes: 0

Rohit Kumar
Rohit Kumar

Reputation: 71

You can use 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

then you can use it like

YourEnum.map(&:to_s) # ["Architects & Engineers", "Doctor/Engineer"]

You can find the enum like

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

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 120990

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

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

Upvotes: 5

Related Questions