How to create nested arrays out of an existing array [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
If I have
arr = ["a", "b", "c", "d", "e", "f"]
how can I make arr equal to this?
[["a", "b"], ["c", "d"], ["e", "f"]]
the goal is to use arr.to_h to make it all into a hash. Thanks!

You can use Hash[]
Hash[*arr] #=> {"a"=>"b", "c"=>"d", "e"=>"f"}
Another option is Enumerable#each_slice
arr.each_slice(2).to_h #=> {"a"=>"b", "c"=>"d", "e"=>"f"}

Related

How to convert every second element of an array into hash value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a string:
string = "a#b#c#d#e#f#g#h#...#z"
I want:
{:a => "b", :c => "d", :e => "f", ...}
First I split the string by doing:
array = string.split("#")
# => [a,b,c,d,e,f.....z]
Then I got stuck. Could anybody help?
Use each_slice to process pairs of elements from the array.
If the array has an even number of elements then calling to_h on the Enumerator returned by each_slice is enough to get the desired result:
string.split('#').each_slice(2).to_h
But to_h above fails if the last slice has only one item.
A general solution uses map to make sure the last slice always contains two items (the second being nil if needed), to prevent to_h fail:
string.split('#').each_slice(2).map{|a,b| [a.to_sym, b]}.to_h
Minor improvement of axiac's answer.
string.split("#").each_slice(2).with_object({}){|(k, v), h| h[k.to_sym] = v}
This does not create temporal arrays.
result_hash = Hash[*string.split("#")]
Here I have remove z from array to make an array with odd elements..
> array = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"]
> Hash[ array.each_slice( 2 ).map { |e| e } ]
#=> {"a"=>"b", "c"=>"d", "e"=>"f", "g"=>"h", "i"=>"j", "k"=>"l", "m"=>"n", "o"=>"p", "q"=>"r", "s"=>"t", "u"=>"v", "w"=>"x", "y"=>nil}

Breaking it down - simple explanation for regular expressions used in ruby exercise [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Problem # 1
In this first problem (line 2) - can someone break it down as to what is happening in terms easy for someone new to Ruby regular expressions to understand?
def encode(string)
string.scan(/(.)(\1*)/).collect do |char, repeat|
[1 + repeat.length, char]
end.join
end
Problem # 2
In this second problem (same answer, but different format to solution) - can someone break it down as to what is happening in terms easy for someone new to Ruby to understand?
def encode(string)
string.split( // ).sort.join.gsub(/(.)\1{2,}/) {|s| s.length.to_s + s[0,1] }
end
It's easy for you to break these down and figure out what they're doing. Simply use IRB, PRY or Sublime Text 2 with the "Seeing is Believing" plugin to look at the results of each operation. I'm using the last one for this:
def encode(string)
string # => "foo"
.scan(/(.)(\1*)/) # => [["f", ""], ["o", "o"]]
.collect { |char, repeat|
[
1 + # => 1, 1 <-- these are the results of two passes through the block
repeat.length, # => 1, 2 <-- these are the results of two passes through the block
char # => "f", "o" <-- these are the results of two passes through the block
] # => [1, "f"], [2, "o"] <-- these are the results of two passes through the block
}.join # => "1f2o"
end
encode('foo') # => "1f2o"
And here's the second piece of code:
def encode(string)
string # => "foobarbaz"
.split( // ) # => ["f", "o", "o", "b", "a", "r", "b", "a", "z"]
.sort # => ["a", "a", "b", "b", "f", "o", "o", "r", "z"]
.join # => "aabbfoorz"
.gsub(/(.)\1{2,}/) {|s|
s.length.to_s +
s[0,1]
} # => "aabbfoorz"
end
encode('foobarbaz') # => "aabbfoorz"

Ruby : How to take the next element of a array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I got this tab :
["aaaaaaaaaaaaaaaaaaa",
"15/87/2014r",
"2453/NRc05",
"xxxxxxxxxxxxxxxxxxxxxxxxxx",
"Adaptée",
"09/12/2013",
"pub.pdf"]
And I only want "xxxxxxxxxxxxx" for example.
I found .next.element(s) but I got no idead of how to use it.. :/
Array#each returns an Enumerator:
arr = [1, 2, 3]
enum = arr.each
enum.next
#=> 1
enum.next
#=> 2
enum.next
#=> 3
enum.next
#=> StopIteration: iteration reached an end
Update
Regarding your comment
I have a array with some datas, and I wanted to save them in a hash with names like... {Name : aaaaa, First Name : bbbbbb} etc etc etc
Rather than calling next over and over again (I assume you are doing something like this):
data = ["John", "Doe"]
enum = data.each
hash = {}
hash[:first_name] = enum.next
hash[:last_name] = enum.next
# ...
You can combine two arrays with Array#zip and convert it to a hash using Array#to_h:
data = ["John", "Doe"]
keys = [:first_name, :last_name, :other]
keys.zip(data).to_h
#=> {:first_name=>"John", :last_name=>"Doe", :other=>nil}

How to convert a string to an array of chars in ruby?

Let's say that you have a string "Hello" and you want an array of chars in return ["H", "e", "l", "l", "o"].
Although it's a simple question I couldn't find a direct answer.
There are several ways to get an array out of a String. #chars which is a shortcut for thestring.each_char.to_a is the most direct in my opinion
>> "Hello".chars
=> ["H", "e", "l", "l", "o"]
The are other ways to get the same result like "Hello".split(//) but they are less intention-revealing.

Combining Array Values (strings) from two different arrays [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to arrays that I would like to combine. For example:
["a", "b", "c", "d"] is one array
["xxxx", "xx", "xxxxx", "x"] is another
My desired output would be a new array that would look like this:
["axxxx", "bxx", "cxxxxx", "dx"]
I'm not quite sure how to combine these two.
Much appreciated.
s = ["a", "b", "c", "d"].zip ["xxxx", "xx", "xxxxx", "x"]
#=> [["a", "xxxx"], ["b", "xx"], ["c", "xxxxx"], ["d", "x"]]
s.map &:join
# => ["axxxx", "bxx", "cxxxxx", "dx"]

Resources