Ruby: Conditionally change the last element in array -
i have array s_ary contains lines of text document. last line may return some_string.
when last line starts return, want line become sv1 = some_string.
my original code 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 improve 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 version change lines start return when last line starts return. still use last version not supposed happen in application, have feeling there must better, more compact way of accomplishing this. somehow, can't find it.
thanks suggestion.
edit: original code need (in agreement second paragraph of 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 wrote confusing. apologies.
why not just:
s_ary[-1].gsub!(/^return /, 'sv1 = ') edit
looking closer @ code, maybe want kind of:
unless s_ary[-1].gsub!(/^return /, 'sv1 = ') s_ary << 'sv1 = last' end the first snippet change last line if starts return, doing nothing otherwise. second snippet change last line if starts return, , append sv1 = last otherwise.
not sure 1 need.
Comments
Post a Comment