'How can I join an array with from and to?
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.
Solution 1:[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
Solution 2:[2]
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
Solution 3:[3]
You can use:
yourList = [1,2,3,4,5]
yourList.shift
puts "#{yourList.join("")}\n\n"
OUTPUT: 2345
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris |
| Solution 2 | |
| Solution 3 | Ygor Rolim |
