Dimych
Dimych

Reputation: 1

Making two-dimensional array from array in Ruby

Its may be question from noob but, but I can't to make it...

I have array

arr = ["I", "wish", "I", "hadn't", "come"]

I need to do

[["I", "wish I hadn't come"], 
 ["I wish", "I hadn't come"],
 ["I wish I", "hadn't come"],
 ["I wish I hadn't", "come"]]

I understand how need to division that array:

Array.new(n) { Array[arr.shift(n).join(" "), arr.join(" ")] }

but n, I think, must change from 1 upto (arr.size - 1) to fill two-dimensional array with needed arrays. How to make it I don't understand.

Upvotes: 0

Views: 68

Answers (4)

Wand Maker
Wand Maker

Reputation: 18772

Here is one way to do this:

require "pp"

arr = ["I", "wish", "I", "hadn't", "come"]

r = (1...arr.size).collect  {|i| [arr.take(i).join(" "), arr.drop(i).join(" ")]}

pp r
#=> [["I", "wish I hadn't come"],
#   ["I wish", "I hadn't come"],
#   ["I wish I", "hadn't come"],
#   ["I wish I hadn't", "come"]]

Upvotes: 0

Pholochtairze
Pholochtairze

Reputation: 1854

This should work for you :

arr = ["I", "wish", "I", "hadn't", "come"]

new_arr = (0..arr.size-2).map {|i| [arr[0..i].join(" "), arr[i+1..-1].join(" ")] }

p new_arr

Which outputs :

[
  ["I", "wish I hadn't come"], 
  ["I wish", "I hadn't come"], 
  ["I wish I", "hadn't come"], 
  ["I wish I hadn't", "come"]
]

Upvotes: 2

libcthorne
libcthorne

Reputation: 417

You may want to consider using slice, which can return a select part of the array, rather than shift, which can achieve the same thing for the first n elements but modifies the original array in doing so. Combining this with your idea of looping from 1 to size-1 will help you reach your goal. The for i in 1..n do syntax is one way of doing this.

Upvotes: 0

Stefan
Stefan

Reputation: 114258

Array#shift is destructive, it alters your array:

arr = ["I", "wish", "I", "hadn't", "come"]

[arr.shift(2).join(" "), arr.join(" ")]
#=> ["I wish", "I hadn't come"]

arr
#=> ["I", "hadn't", "come"]

You can use Array#[] instead:

arr = ["I", "wish", "I", "hadn't", "come"]

arr[0..2]
#=> ["I", "wish", "I"]

arr[3..-1]
#=> ["hadn't", "come"]

-1 refers to the last element.

Upvotes: 1

Related Questions