Reşit Körsu
Reşit Körsu

Reputation: 598

Why my ruby #each block is not working as a one-liner

this is the block i wrote:

  half.each { |x| array << x count+=1 } 

it just doesnt work like this but it works very good if i write it the "do...end" way:

 half.each do |x| 
    array << x 
    count+=1 
    end 

it's not really important since i can work my whole method in the long way but i want to understand the one-liner ways of ruby. Thanks already.And if needed this is the whole method:

def length_even(array)
  half = array[(0...array.length/2)]
  count = 0
  half.each do |x| 
    array << x 
    count+=1 
    end 
  p array.drop(count).join
end

Upvotes: 1

Views: 218

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54243

Solution

What's the goal of your method? Do you want to split your array in 2 and switch both halves? Array#rotate does exactly that :

def length_even(array)
  array.rotate(array.length/2).join
end

puts length_even([0,1,2,3,4,5]) #=> "345012"

Now you have your one-liner ;)

Notes

  • If you use p at the end of your method, it will always display it before returning it. It might not always be desirable. It's still better than puts though, because your method would return nil otherwise.

  • Your code modifies array, which you might not want to do.

  • each returns the original array, so you could use count = half.each{|x| array << x}.size

  • count is just 1+array.length/2, so you don't need the previous code either.

  • You might want to use join with a space, to see the difference between [1,2,3] and [12,3]

  • Finally, rotate might be hard to find in the documentation. But you already know about drop, and drop mentions take.

So your code could become :

def length_even(array)
  half_size = array.length/2
  (array.drop(half_size)+array.take(half_size)).join(' ')
end

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230396

half.each { |x| array << x count+=1 }

Your statements are not separated here. Normally, linebreak serves as a separator. But if you want to put several statements on the same line, use ;

  half.each { |x| array << x; count+=1 } 

Upvotes: 1

Related Questions