Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to keyword

We can easily convert a keyword into a string:

true.to_s
=> "true"

But how to convert a string into a keyword?

like image 760
sivabudh Avatar asked Sep 09 '26 11:09

sivabudh


1 Answers

How many keywords do you have? What's your definition of a 'keyword'?

I would implement with a case-command. You may define a to_keyword method for String. My implementation detects true, false, nil (or NULL). The strings are detected, ignoring capitals (TRUE will also be true) Other strings will return a symbol (The string itself would be another reasonable result).

The example can be adapted for further 'keywords' or other results.

class String
  #Return 'keyword'
  #Detects:
  #- true (independend of lower letters/capitals)
  #- false (independend of lower letters/capitals)
  #- nil/NULL (independend of lower letters/capitals)
  def to_keyword
    case self
      when /\Atrue\Z/i; true
      when /\Afalse\Z/i; false
      when /\Anil\Z/i, /\ANULL\Z/; nil
      else; self.to_sym #return symbol. Other posibility: self.
    end
  end
end


p 'true'.to_keyword #true
p 'TRUE'.to_keyword #true
p 'false'.to_keyword #false
p 'NULL'.to_keyword #nil  (NULL is used in DB like nil)
p 'NULLc'.to_keyword #:NULLc  not detected -> symbol
like image 157
knut Avatar answered Sep 11 '26 20:09

knut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!