Ruby: Conditionally change the last element in array

arrays, ruby

Solution

Why not just:

s_ary[-1].gsub!(/^return /, 'sv1 = ')

EDIT

Looking closer at your code, maybe what you want is kind of:

unless s_ary[-1].gsub!(/^return /, 'sv1 = ')
  s_ary << 'sv1 = last'
end

The first snippet will only change the last line if it starts with return, doing nothing otherwise. The second snippet will change the last line if it starts with return, and will append `sv1 = last` otherwise.

Not sure which one you need.

Problem

I have an array `s_ary` that contains all the lines of a text document. The last line may be something like `return some_string`. When the last line starts with `return`, I want the line to become `sv1 = some_string`. My original code does exactly what I need: ``` if s_ary.last =~ /^[\s]*return/ t = s_ary.last.gsub(/^[\s]*return/, 'sv1 = ') s_ary.pop s_ary << t else s_ary << 'sv1 = last' end ``` I tried to improve it with: ``` if s_ary.last =~ /^[\s]*return/ s_ary.map! {|x| (x =~/return/) ? x.gsub(/return/, 'sv1 = ') : x } else s_ary << 'sv1 = last' end ``` But this version will change all the lines that start with `return` when the last line starts with `return`. I could still use this last version as this is not supposed to happen in my application, but I have the feeling that there must a better, more compact way of accomplishing this. Somehow, I can't find it. Thanks for any suggestion. EDIT: The original code that does exactly what I need is actually (in agreement with the second paragraph of this post): ``` if s_ary.last =~ /^[\s]*return/ t = s_ary.last.gsub(/^[\s]*return/, 'sv1 = ') s_ary.pop s_ary << t end ``` I can't believe I wrote something so confusing. My apologies.

Original source