1

I have an array:

arr2 = [6, '(7,0)', '(15,0)', '(5,0)', 3, '(15,2)', 17]

I want to parse each element of the array and get the value as follows:

arr2 = [6, 0, 0, 0, 3, 2, 17]

means if the array element is like (15,2) then only the second element i.e 2 should get printed in the response, and if the array element is not in the format like (7,0) then it should be printed as it is.

3
  • 1
    arr2 is an invalid structure in Ruby. Commented Dec 30, 2016 at 7:36
  • @sagarpandya82, you can covert this array into a string type as follows: arr2 = %w[6, (7,0), (15,0), (5,0), 3, (15,2), 17] Commented Dec 30, 2016 at 7:43
  • 1
    You’ve been told already that [6, (7,0), (15,0), (5,0), 3, (15,2), 17] is not a valid ruby object and you again come with it. Downvoted and voted to close. Commented Dec 30, 2016 at 7:56

3 Answers 3

3
arr = [6, '(7,0)', '(15,0)', '(5,0)', 3, '(15,2)', 17]

arr.map do |obj|
  case obj
  when Integer
    obj
  else
    obj[/(?<=,)\d+/].to_i
  end
end
  #=> [6, 0, 0, 0, 3, 2, 17]
Sign up to request clarification or add additional context in comments.

Comments

3
[6, [7,0], [15,0], [5,0], 3, [15,2], 17].map { |e| [*e].last }
#⇒ [6, 0, 0, 0, 3, 2, 17]

If the elements are strings:

%w[6, (7,0), (15,0), (5,0), 3, (15,2), 17].map { |e| e[/\d+(?=\)|,?\z)/] }
#⇒ ["6", "0", "0", "0", "3", "2", "17"]

map(&:to_i) the latter to get an array of integers.


Finally, for the up-to-date version:

[6, '(7,0)', '(15,0)', '(5,0)', 3, '(15,2)', 17].
    map { |e| e.to_s[/\d+(?=\)|,?\z)/] }.
    map(&:to_i)
#⇒ [6, 0, 0, 0, 3, 2, 17]

Exotics:

[6, '(7,0)', '(15,0)', '(5,0)', 3, '(15,2)', 17].
    inspect.
    scan(/\d+(?:,\d+)?/).
    map { |e| e.split(',').last.to_i }
#⇒ [6, 0, 0, 0, 3, 2, 17]

2 Comments

%w syntax does not require commas, just write %w[6 (7,0) ...
@akuhn “%w syntax does not require commas”—good to know, thank you.
3

This seems fine to me:

arr2.map{|x| x.to_s.scan(/\d+/).last.to_i }

And if you want something without regexp:

arr2.map do |item|
  item.is_a?(Integer) ? item : item[1+item.rindex(',')..-2].to_i 
end

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.