Search code examples
ruby-on-railsrubystringobjectuuid

Convert a string representation of UUIDTools:UUID back to UUIDTools:UUID


I have a scenario, where in I have a uuid in a string format. This uuid originally belonged to UUIDTools::UUID class (and was already converted to_s before passing on to my method). Now, I need to convert it back to object of type - UUIDTools::UUID, as I need to invoke few methods specific to UUIDTools::UUID class. Any clean way of doing this?

Thanks in advance!


Solution

  • Just use UUIDTools::UUID.parse:

     require "uuidtools"
    
     uuid = UUIDTools::UUID.random_create
     uuid.to_s
     #=> "cd833ba3-97c5-4615-a2a0-a6c3e56b24b2"
    
     UUIDTools::UUID.parse("cd833ba3-97c5-4615-a2a0-a6c3e56b24b2")
     #=> <UUID:0x3fd33d0ac184 UUID:cd833ba3-97c5-4615-a2a0-a6c3e56b24b2>
    
     UUIDTools::UUID.parse(uuid.to_s) == uuid
     #=> true