3

If I have an array of strings in ruby and I want to get the resulting array, what is the best way of doing it?

array = ["string_apple", "string_banana", "string_orange"]

desired_result = [["string", "apple"], ["string", "banana"], ["string", "orange"]]

My current attempt:

array.map(|r| r.split("_"))

4
  • @TimurShtatland Added Commented Dec 7, 2020 at 16:28
  • 1
    Your current attempt is fine except that you should use curly braces for the block in map. . Note that it doesn't change the array. Maybe you just need to assign it to a variable. new_array = array.map { |r| r.split("_") } or if you want to use the same variable name array = array.map {|r| r.split("_") } Commented Dec 7, 2020 at 16:35
  • @SteveTurczyn There is no such syntax in ruby .map(|r| r.split("_")). Language Rust has that syntax. Commented Dec 7, 2020 at 16:37
  • Sure there is, except it needs curly braces as I said in my comment. Commented Dec 7, 2020 at 17:36

1 Answer 1

3

You need map{...}, not map(...) for correct syntax in Ruby here:

array = ["string_apple", "string_banana", "string_orange"]

# Assign to a different array:
split_array = array.map{ |s| s.split(/_/) }

# Or modify the original array in place:
array.map!{ |s| s.split(/_/) }

# [["string", "apple"], ["string", "banana"], ["string", "orange"]]
Sign up to request clarification or add additional context in comments.

2 Comments

I had to add and exclamation to the map to override the array value .map!
@SteveG Thank you for the comment! Added map! to the answer.

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.