Ruby: Check If Object Is Nil

Ruby: check if object is nil

You seem to have a few questions here, so I'll take a stab at what seems to be the main one:

If you want to see if something is nil, just use .nil? - so in your example, you can just say request.nil?, which returns true if it is nil and false otherwise.

How to check if an object is nil in a view in Ruby?

How about:

<% if !@foo.nil? && !@foo.new_record? %>
Hello!
<% end %>

First off, you need to be using AND logic rather than OR logic here, since any ActiveRecord object meets at least one the requirements of "not nil" or "not a new record".

Second, checking for nil first ensures that the second check isn't run if the first one fails. The error is thrown because you can't use #new_record? on an object that doesn't support it, so checking for nil first ensures that that method is never run on a nil.

Checking if a variable is not nil and not zero in ruby


unless discount.nil? || discount == 0
# ...
end

Ruby: if !object.nil? or if object

There are differences. For example:

false.nil?
# => false

So:

if !false.nil?
'foo'
end
# => "foo"

if false
'foo'
end
# => nil

As @tokland suggested, in most cases using !obj.nil? construction is unnecessary.

How I can check if an object is null in ruby on rails 2?

it's nilin Ruby, not null. And it's enough to say if @objectname to test whether it's not nil. And no then. You can find more on if syntax here:

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#if

Check if Object is nil and needed attribute is nil or empty

What about this?

data = response.try(:[], 'data')
raise Exception, "Response is not valid" if data.nil? || data.empty?

As @ksol correctly mentions in the comments, try helper comes from ActiveSupport. But it is not difficult at all to re-implement.

class Object
def try method, *args
if respond_to? method
send method, *args
else
nil
end
end
end

class Foo
def hello name
"hello #{name}"
end
end

f = Foo.new
f.try(:bar) # => nil
f.try(:hello, 'world') # => "hello world"
nil.try(:wat) # => nil

Alternatives

Here's Object#andand if you don't want to drag along the entire activesupport and don't feel like writing code that's already written.

data = response.andand['data']
raise Exception, "Response is not valid" if data.nil? || data.empty?

How to check for nil and compare if != nil on Hashes?

If you want to check if an object/value is nil you can do it like this:

object.nil?

in your case (the value of a hash is something like): your_hash[key].nil?, with that said if you want to do something if the value is not nil you can do:

if !my_hash[my_key].nil?
end

or the ruby way:

unless my_hash[my_key].nil?
end

Also if you want to know whether a hash contains or not a key you can do it as follow:

your_hash.keys.include? key_to_search

If you want to compare 2 strings: str1 == str2, if you want to know if str1 contains to str2 as substring then str1.include? str2

Ruby check if block is nil

It is unclear what you are asking, because a block itself can not be empty. Therefore, you might mean a few different things:

  1. A missing block. You can check if a block is given

    block_given?
  2. Block with empty body (aka {} or do end). This is not impossible, but requires some advanced voodoo ruby metaprogramming magic. Generally, if this is what you are looking for, either you are writing something very interesting or your approach is completely wrong.
  3. You want to check if the result of executing a block is "empty" without invoking it first. This is impossible. For example, consider the following block:

    { [nil, "", true].sample }

    Obviously, there is no way to know in advance.

  4. You are ok with calling the block. Then you can assign the result to a variable and make checks on it:

    def some_method
    evaluation_result = yield if block_given?
    if evaluation_result.nil? or evaluation_result == ""
    # do something if the block was not given or the result is nil/empty
    puts "Empty block? Seriously?"
    else
    # do something if the block was given and the result is non nil/empty
    puts evaluation_result
    end
    end

    Now when you invoke some_method:

    some_method { "something" } # => "something"
    some_method { 3 + 5 } # => 8
    some_method { nil } # => "Empty block? Seriously?"
    some_method { "" } # => "Empty block? Seriously?"
    some_method { } # => "Empty block? Seriously?"
    some_method # => "Empty block? Seriously?"

EDIT:
A workaround for case #3 might be to create two procs, one with what you want to do if the block is "empty" and one - if it is not, then pass them around to the endpoint where you will finally invoke the block. This might or might not be applicable depending on your exact situation.

EDIT2:
Another workaround can be to redefine the Proc#call method for your proc instances. However, this doesn't work for yield:

def secure(&block)
insecure_call = block.method(:call)
block.define_singleton_method(:call) do
insecure_call_result = insecure_call.call
if insecure_call_result.nil? or insecure_call_result == ""
"<b>Bummer! Empty block...</b>"
else
insecure_call_result
end
end
end

x = proc { }
y = proc { "" }
z = proc { nil }
a = proc { 3 + 5 }
b = proc { "something" }
u = proc { [nil, "", true].sample }
[x, y, z, a, b, u].each { |block| secure &block }

# some method that uses the block
def user(&block)
"What I got is #{block.call}!"
end

user &x # => "What I got is <b>Bummer! Empty block...</b>!"
user &y # => "What I got is <b>Bummer! Empty block...</b>!"
user &z # => "What I got is <b>Bummer! Empty block...</b>!"
user &a # => "What I got is 8!"
user &b # => "What I got is something!"
user &u # => Different each time

EDIT3: Another alternative, which is sort of cheating, is to wrap the given proc in another proc. This way, it will work for yield too.

def wrap(&block)
proc do
internal_proc_call_result = block.call
if internal_proc_call_result.nil? or internal_proc_call_result == ""
"<b>Bummer! Empty block...</b>"
else
internal_proc_call_result
end
end
end

Now using the result of wrap and will get you behavior similar to secure.



Related Topics



Leave a reply



Submit