MaoTse
MaoTse

Reputation: 61

How to update the first element of an array in Ruby on Rails?

I'm not a Ruby on Rails developer, like pretty much zero experience.

In a very complex context, I've got this process where I'm replacing commas by semi-colons and also adding a wrapper (double quotes) to each element of an array:

@wrap_char = '"'

def escape(text)
  if text.present?
    @wrap_char + text.to_s.tr(',', ';') + @wrap_char
  else
    @wrap_char + @wrap_char
  end
end

['2','SE','STKT','','','',''].map(&method(:escape)).join(',') << "\n"

returning this: "2","SE","STKT","","","",""

My problem is that I need to exclude the first element from being wrapped, in order to get: 2,"SE","STKT","","","",""

Ideas will be highly appreciated!

Upvotes: 1

Views: 329

Answers (2)

Lam Phan
Lam Phan

Reputation: 3811

wrap_char = "\""
converts = ['2','SE','STKT','','','',''].map { |x| 
  x =~ /[+-]?[0-9]+/ ? x : "#{wrap_char}#{x.to_s.tr(',', ';')}#{wrap_char}" 
}
puts converts.join(",")
# 2,"SE","STKT","","","",""

Upvotes: 0

mu is too short
mu is too short

Reputation: 434616

First of all nil.to_s is '' so you could simplify your escape method to:

def escape(text)
  @wrap_char + text.to_s.tr(',', ';') + @wrap_char
end

A straight forward approach would be something like this:

a = ['2', 'SE', 'STKT', '', '', '', '']
(a[0, 1] + a[1..].map(&method(:escape))).join(',')

That'll work as long as a is not empty. If you want to allow for a to be empty then you can take advantage of [][1..] being nil and nil.to_a being an empty array:

(a[0, 1] + a[1..].to_a.map(&method(:escape))).join(',')

You could also say:

(a[0..0] + a[1..].to_a.map(&method(:escape))).join(',')

but the 0..0 range keeps looking at me funny so I prefer a[0, 1]. You could also use #slice if you don't like the brackets:

(a.slice(0, 1) + a.slice(1..).to_a.map(&method(:escape))).join(',')

You could also put the "leave the first element alone" logic inside the iteration with things like:

a.map.with_index { |e, i| i > 0 ? escape(e) : e }.join(',')

Upvotes: 2

Related Questions