Ruby/Rails does lots of cool stuff when it comes to sugar for basic things, and I think there\'s a very common scenario that I was wondering if anyone has done a helper or s
There's no "do this the (first|last) time" syntax in Ruby. But if you're looking for succinctness, you could do this:
a.each_with_index do |x, i|
print (i > 0 ? (i == a.length - 1 ? x*10 : x) : x+1)
end
The result is what you'd expect:
irb(main):001:0> a = Array.new(5,1)
=> [1, 1, 1, 1, 1]
irb(main):002:0> a.each_with_index do |x,i|
irb(main):003:1* puts (i > 0 ? (i == a.length - 1 ? x*10 : x) : x+1)
irb(main):004:1> end
2
1
1
1
10
If the code for the first and last iteration has nothing in common with the code for the other iterations, you could also do:
do_something( a.first )
a[1..-2].each do |x|
do_something_else( x )
end
do_something_else_else( a.last )
If the different cases have some code in common, your way is fine.
If you know the items in the array are unique (unlike this case), you can do this:
a = [1,2,3,4,5]
a.each_with_index do |x, i|
if x == a.first
print x+1
elsif x == a.last
print x*10
else
print x
end
end
You could grab the first and last elements and process them differently, if you like.
first = array.shift
last = array.pop
process_first_one
array.each { |x| process_middle_bits }
process_last_one