开发者

Convert string to keyword

We can easily convert a keyword into a string:

true.to_s
=> "true"

But how to convert a 开发者_Python百科string into a keyword?


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


try this:

ruby-1.9.2-p136 :001 > true
 => true 
ruby-1.9.2-p136 :002 > eval("true")
 => true


You could try yaml:

require "yaml"
p YAML.load('true')
p YAML.load('TRUE')
p YAML.load('false')
p YAML.load('nil')
p YAML.load('NULL') #nil


I like Knut's answers mostly. I don't think I would support "Null" and others though. Here is this version which is a little more simple.

class String
  def to_keyword
    self == "true"
  end
end

>> "true".to_keyword
=> true
>> "false".to_keyword
=> false

This problem is pretty straight forward though. In your tests you could simply

:correct => (true_string == "true")


Following your comment, you could do something like that :

true_string = "true"

:correct => !!true_string

# examples
!true_string #=> false
!!true_string #=> true
!!!true_string #=> false
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜