1

I have an array, I would like to concat all values except the first one element.

For example: Doing it on the array [1,2,3,4,5] should output 2345

I tried to do it with row.join("") but I could not figure out how to do it.

1
  • 3
    I think you mean that "2345" (not 2345) is to be returned. Be precise! Jan 26, 2022 at 19:49

4 Answers 4

7

Try these

[1,2,3,4,5].drop(1).join
=> "2345"

[1,2,3,4,5][1..-1].join
=> "2345"
3
  • 1
    With recent versions of Ruby you can write [1,2,3,4,5][1..].join (or [1,2,3,4,5].join[1..]). Jan 26, 2022 at 21:05
  • 1
    @CarySwoveland Didn't know! Interestingly enough [1,2,3,4,5][1...].join (3 dots) gives the same result. Jan 26, 2022 at 21:10
  • That's because the concept of "inclusive" and "exclusive" doesn't apply to infinity.
    – Stefan
    Jan 27, 2022 at 17:36
1

Your question almost certainly just suffers from poor formatting, but if you actually want a number back rather than a string, you could do something like:

irb(main):018:0> a = [1, 2, 3, 4, 5]
irb(main):019:0> num = 0
irb(main):020:0> a.drop(1).reverse.each_with_index { |digit, i| num += digit * 10 ** i }
=> [5, 4, 3, 2]
irb(main):021:0> num
=> 2345

Or perhaps:

irb(main):033:0> a = [1, 2, 3, 4, 5]
irb(main):034:0> a.drop(1).reverse.each_with_index.reduce(0) { |acc, (x, i)| acc + x * 10 ** i }
=> 2345
4
  • 2
    You can reduce the number of temporary arrays by one (to one) by writing a.drop(1).reverse_each.with_index.reduce(0) { |acc, (x, i)| acc + x * 10 ** i }, but isn't a.drop(1).join.to_i a lot simpler? Jan 26, 2022 at 21:02
  • 1
    a[1..].inject{|res, d| res * 10 + d } seems to work without reversing and exponentiation.
    – steenslag
    Jan 26, 2022 at 22:52
  • 1
    This seems overly complicated. If the required output should be in number form, why not just use [1,2,3,4,5].drop(1).join.to_i?
    – user16452228
    Jan 27, 2022 at 0:10
  • I was trying to avoid string manipulation. Alternative suggestions have been made by some very smart people that accomplish that in more clever ways than I did.
    – Chris
    Jan 27, 2022 at 0:13
1

Here's another approach using the * or "splat" operator and multiple_assignments:

dropped, *kept =  [1,2,3,4,5]
kept.join
#=>  "2345"

The splat can be used to deconstruct the array in a plethora of other ways as well such as:

drop, drop, *keep =  [1,2,3,4,5]
keep  #=>  [3, 4, 5]

*keep, drop =  [1,2,3,4,5]
keep  #=>  [1, 2, 3, 4]

first,*middle, last =  [1,2,3,4,5]
first #=>  1
middle  #=>  [2, 3, 4]
last  #=>  5

...just to name a few

0

You can use:

yourList = [1,2,3,4,5]
yourList.shift
puts "#{yourList.join("")}\n\n"

OUTPUT: 2345

1
  • 3
    Be careful, shift modifies the original array. Jan 26, 2022 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.