Ask Your Question

add character to first and last array elements in ruby

asked 2018-08-31 03:29:12 -0600

gilbo gravatar image


I'm trying to format the output of a custom fact in ruby.

I've got this array:

array = [ "a", "b", "c", "d", "e", "f", "g", "h" ]

what i'd like to do is add a character to the first and last elements, so i end up with:

[ "na", "b", "c", "d", "e", "f", "g", "hn" ]

I've tried all sorts of ways using an if array.first? or array.last? conditions in a map! statement but just can't seem to get there. Any help appreciated!


edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2018-10-08 14:48:48 -0600

In Ruby you can do nice stunts with ranges and negative indices:

['n' + array[0]] + array[1..-2] + [array[-1] + 'n']

I hope, you are _absolutely_ sure the first and last array's elements are strings, otherwise the + operator could be invalid.

edit flag offensive delete link more


throw in a `.to_s` to be sure!

DarylW gravatar imageDarylW ( 2018-10-09 07:45:33 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2018-08-31 03:29:12 -0600

Seen: 102 times

Last updated: Oct 08