简体   繁体   English

Ruby字符串“ nil”转换为nil:NilClass nil(与nil.inspect相反)

[英]Ruby string “nil” to nil:NilClass nil (reverse of nil.inspect)

I wonder howto get from a string "nil" the nil:NilClass? 我想知道如何从字符串“ nil”获得nil:NilClass吗?

nil.inspect -> "nil"

I wish something like: 我希望像这样:

"nil".to_nil -> nil

Update: 更新:

As I write in the comment bellow it's easier to : 正如我在下面的评论中写道:

params[:form].each_pair{|k,v| fields[k] = k.to_s.include?('_id') ? v.to_nil : v

then 然后

params[:form].each_pair{|k,v| fields[k] = k.to_s.include?('_id') ? (v == "nil" ? nil : v) : v }

I don't see the point of a to_nil , because well, it's always nil , so write nil . 我看不到to_nil ,因为好吧,它总是nil ,所以写nil But if your question is which is the inverse operation of inspect , you can use eval : 但是,如果您的问题是inspect的逆运算,则可以使用eval

eval("nil") #=> nil

Re-open the string class if you want this functionality globally. 如果要全局使用此功能,请重新打开字符串类。

class String
  def to_nil
    if self == 'nil'
      nil
    else
      self
    end
  end
end

'nil'.to_nil # => nil
'another string'.to_nil # => "another string"

You could eval the string "nil" for example: 您可以评估字符串“ nil”,例如:

=> eval("nil").nil?
irb> true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM