Question

I'm trying to reduce the while loop below to a single line

def this_method(week)
  i = 0
  while i < array.length
    yield(week[i])
    i += 1
  end
end

week.each do |week|
  puts week
end
Was it helpful?

Solution

Like others, I'm confused about the example (array is not defined, and this_method is never called). But you certainly don't need the while loop. I'd just use the Integer#times method, since you're making no use of the array values:

array.length.times {|i| yield week[i]}

#each_index (which ram suggested) works just as well.

But if array is actually meant to be week, then it gets even simpler:

week.each {|x| yield x}

I'm not sure why you'd want to create a method that just recycles #each though.

OTHER TIPS

For since line you can use Array#each_index:

array.each_index {|i| yield week[i] }

No, you can't. The ternary operator is a conditional expression, the while is a loop expression.

However, in Ruby you normally use enumerators, not while. Your code can be rewritten as

def this_method(week)
  array.each_with_index { |item, i| yield(week[i]) }
end

What is not clear to me, is there the array variable comes from. Even in your example, there is no definition of such variable.

if in any form check conditions only once.
while on other hand, can check conditions many times.

Well, if you don't like other answers with enumerators you can use while in a different form:

def this_method(week)
  i = -1
  yield(week[i]) while (i+=1) < array.length
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top