35
<% if dashboard_pane_counter.remainder(3) == 0 %>
  do something
<% end>

If dasboard_pane_counter wasn't defined, how can I get this to evaluate to false rather than throw an exception?

6 Answers 6

52
<% if defined?(:dashboard_pane_counter) && dashboard_pane_counter.remainder(3) == 0  %>
  # do_something here, this assumes that dashboard_pane_counter is defined, but not nil
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

symbol did not work for me. so i had to check this way if defined?(variable_name)
5

When using rails and instance variables, nil has a try method defined, so you can do:

<% if @dashboard_pane_counter.try(:remainder(3)) == 0  %>
   #do something
<% end %>

so if the instance variable is not defined, try(:anything) will return nil and therefore evaluate to false. And nil == 0 is false

4 Comments

This will still cause an error if the variable hasn't been defined, so doesn't answer the question.
No it won't, rails has 'magic built in': 1.9.3p392 :005 > @hh => nil 1.9.3p392 :006 > @hh.try(:anything) => nil
So for instance variables, nil has a 'try' method
Ah, you're right, my mistake. If you edit your answer to that clear I can remove my down vote.
5

local_assigns can be used for that, since this question is from a few years ago, I verified that it exists in previous versions of rails

<% if local_assigns[:dashboard_pane_counter] 
                 && dashboard_pane_counter.remainder(3) == 0%>
<% end %>

It's in the notes here

http://apidock.com/rails/ActionController/Base/render

Comments

0

Posting this answer for beginner coders like myself. This question can be answered simply using two steps (or one if using &&). It is a longer and less pretty answer but helps new coders to understand what they are doing and uses a very simple technique that is not present in any of the other answers yet. The trick is to use an instance (@) variable, it will not work with a local variable:

if @foo
  "bar"
end

If @foo is defined it will be return "bar", otherwise not (with no error). Therefore in two steps:

if @dashboard_pane_counter
  if @dashboard_plane_counter.remainder(3) == 0
    do something
  end
end

Comments

-1

Another way, with a neat gem, is 'andand.'

https://github.com/raganwald/andand

Comments

-3

Insted of

if !var.nil?

I would use

unless var.nil?

Thats much better ruby code!

1 Comment

this only applies if the variable was defined previous to this code. Try if !adallajglaksdkfaj.nil? on the first line of a "function". kablammo :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.