3

I have three arrays, two of which come from JSON.

I need to check if each array is not nil and the count is greater than 0. If any are greater than 0 display "Hello World" else display "Boo".

<% if [email protected]? && @arrayOne.count > 0 || !@user_json[:user_stuff].nil? && @user_json[:user_stuff].count > 0 || !@user_json[:more_user_stuff].nil? && @user_json[:more_user_stuff].count > 0 %>
<h1>Hello World</h1>
  <% else %>
<h1>Boo</h1>
<% end %>

I need some help refactoring this code and would like to learn other ways to approach this.

4 Answers 4

5

You can use array.blank? (assuming you're using Rails of course) to check whether an array is nil or empty, such as:

<% if [email protected]? || !@user_json[:user_stuff].blank? || !@user_json[:more_user_stuff].blank? %>

Rule of thumb you should move as much logic to the controller as you can.


As suggested in the comments, you can also use present?, which is the same as !blank?, improving readability a bit:

<% if @arrayOne.present? || @user_json[:user_stuff].present? || @user_json[:more_user_stuff].present? %> 
Sign up to request clarification or add additional context in comments.

5 Comments

If the @arrayOne is nil, this will throw NoMethodError: undefined method 'blank?' for nil:NilClass. (Same for @user_json[:user_stuff], @user_json[:more_user_stuff])
@falsetru do you mean if @arrayOne etc are undefined? AFAIK blank? tests for nil before testing empty, such that nil.blank? returns true.
@falsetru blank? is a Rails API function, not a Ruby core function. Calling blank? in irb will in fact result in the undefined error.
!foo.blank? could be written as foo.present?. What reads much nice IMHO.
It's not necessary to use Rails to take advantage of blank? or present?. See stackoverflow.com/questions/4238867/….
3

You can use Enumerable#all?:

<% if [!@arrayOne, @user_json[:user_stuff], @user_json[:more_user_stuff]].all? { |x|
  x && x.count > 0
} %>
  ...

Comments

1

I would start with something like this:

if [@arrayOne, @user_json[:user_stuff], @user_json[:more_user_stuff]].any?(&:present?)

In a next step I would move that condition into a helper with a nice name. Unfortunately you did not provide why you need this check (that why would hint a good name). But as an idea:

# in a helper
def something_to_show?
  [ @arrayOne, @user_json[:user_stuff], @user_json[:more_user_stuff]
  ].any?(&:present?)
end

# in the view
<% if something_to_show? %>
  <h1>Hello World</h1>
<% else %>
  <h1>Boo</h1>
<% end %>

Comments

0

A simple way that doesn't require Rails:

puts [a, b, c].map(&:to_a).all?(&:empty?) ? 'Boo' : 'Hello World'

Comments

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.