1

I have some array

>> a = ["a..c", "0..2"]
=> ["a..c", "0..2"]

I need convert this array to another array

>> b = ("a".."c").to_a + (0..2).to_a
=> ["a", "b", "c", 0, 1, 2]

How I can do it?

3 Answers 3

3
a.flat_map do |string_range| 
  from, to = string_range.split("..", 2)
  (from =~ /^\d+$/ ? (from.to_i..to.to_i) : (from..to)).to_a 
end 
#=> => ["a", "b", "c", 0, 1, 2]
Sign up to request clarification or add additional context in comments.

Comments

2

what about this?

a = ["a..c", "0..2"]

b = a.map { |e| Range.new( *(e).split('..') ).to_a }.flatten

no flat_map used so it works the same on all versions

as @steenslag correctly mentioned, this version does not convert to integers.

here is a version that does:

b = a.map do |e| 
  Range.new( *(e).split('..').map{ |c| c =~ /\A\d+\Z/ ? c.to_i : c } ).to_a 
end.flatten

see it in action here

1 Comment

Thanx, I have 1.8.7 version of Ruby and this example is worked!
2
a = ["a..c", "0..2"]
b = a.flat_map{|str| Range.new(*str.split('..')).to_a} # => ["a", "b", "c", "0", "1", "2"]
p b.map!{|v| Integer(v) rescue v} # => ["a", "b", "c", 0, 1, 2]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.