kfl62
kfl62

Reputation: 2514

Ruby string "nil" to nil:NilClass nil (reverse of nil.inspect)

I wonder howto get from a string "nil" the 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 }

Upvotes: 0

Views: 1213

Answers (3)

tokland
tokland

Reputation: 67850

I don't see the point of a to_nil, because well, it's always nil, so write nil. But if your question is which is the inverse operation of inspect, you can use eval:

eval("nil") #=> nil

Upvotes: 4

martido
martido

Reputation: 383

You could eval the string "nil" for example:

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

Upvotes: 0

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

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"

Upvotes: 1

Related Questions