Leo
Leo

Reputation: 2103

proper formatting in long fragments of code

if i have to use unless/if and blocks, code might get really long. This doesnt look nice at all, and my question is how to handle this kind of situation, what is the proper formatting, eg in this hipothetical case?

if some_array.each.all? {|argument| argument.method_one == @some_value} && another_array.method_two == @completely_different_value

    #
    #some stuff here
    #

end

Upvotes: 1

Views: 130

Answers (3)

Patrick Oscity
Patrick Oscity

Reputation: 54684

I recommend extracting the parts into variables

condition1 = some_array.each.all? do |argument|
  argument.method_one == @some_value
end

condition2 = another_array.method_two == @completely_different_value

if condition1 && condition2
    #
    # some stuff here
    #
end

or making the conditions into methods

def condition1?(arr)
  arr.some_array.each.all? do |argument|
    argument.method_one == @some_value
  end
end

def condition2?(arr)
  arr.method_two == @completely_different_value
end

if condition1?(some_array) && condition2?(another_array)
    #
    # some stuff here
    #
end

extracting into methods has the advantage that your code generally becomes easier to test.

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

There are plenty ways to accomplish your task.

The most common way is to use backslashes as you do in shell prompt:

if some_array.each.all? { |argument| \
    argument.method_one == @some_value \
  } \
  && another_array.method_two == @completely_different_value \

 puts a
end  

Also you may silently break the line at dots (dot must be placed at the end of the line in Ruby < 1.9 or at the beginning of the next line as well in Ruby 1.9+.)

"foo bar baz".
  reverse.
  split.
  map(&:capitalize).
  join ' '
# ⇒ "Zab Rab Oof"

Upvotes: 0

megas
megas

Reputation: 21791

You can divide it in several lines. I think this format is more easier to read

result1 = some_array.each.all? { |argument| argument.method_one == @some_value }
result2 = another_array.method_two == @completely_different_value
if result1 && result2
  #
  #some stuff here
  #
end

Upvotes: 1

Related Questions