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.
Try these
[1,2,3,4,5].drop(1).join
=> "2345"
[1,2,3,4,5][1..-1].join
=> "2345"
[1,2,3,4,5][1..].join
(or [1,2,3,4,5].join[1..]
).
Jan 26, 2022 at 21:05
[1,2,3,4,5][1...].join
(3 dots) gives the same result.
Jan 26, 2022 at 21:10
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
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
a[1..].inject{|res, d| res * 10 + d }
seems to work without reversing and exponentiation.
Jan 26, 2022 at 22:52
[1,2,3,4,5].drop(1).join.to_i
?
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
You can use:
yourList = [1,2,3,4,5]
yourList.shift
puts "#{yourList.join("")}\n\n"
OUTPUT: 2345
"2345"
(not2345
) is to be returned. Be precise!