How to convert a string to an array of chars in ruby? - 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.

Related

Zip all array values of hash

I'd like to zip all the array values of a hash. I know there's a way to zip arrays together. I'd like to do that with the values of my hash below.
current_hash = {:a=>["k", "r", "u"],
:b=>["e", " ", "l"],
:c=>["d", "o", "w"],
:d=>["e", "h"]
}
desired_outcome = "keder ohulw"
I have included my desired outcome above.
current_hash.values.then { |first, *rest| first.zip(*rest) }.flatten.compact.join
An unfortunate thing with Ruby zip is that the first enumerable needs to be the receiver, and the others need to be parameters. Here, I use then, parameter deconstruction and splat to separate the first enumerable from the rest. flatten gets rid of the column arrays, compact gets rid of the nil (though it's not really necessary as join will ignore it), and join turns the array into the string.
Note that Ruby zip will stop at length of the receiver; so if :a is shorter than the others, you will likely have a surprising result. If that is a concern, please update with an example that reflects that scenario, and the desired outcome.
Here I'm fleshing out #Amadan's remark below the horizontal line in is answer. Suppose:
current_hash = { a:["k","r"], b:["e"," ","l"], c:["d","o","w"], d:["e", "h"] }
and you wished to return "keder ohlw". If you made ["k","r"] and [["e"," ","l"], ["d","o","w"], ["e", "h"]] zip's receiver and argument, respectively, you would get "keder oh", which omits "l" and "w". (See Array#zip, especially the 3rd paragraph.)
To include those strings you would need to fill out ["k","r"] with nils to make it as long as the longest value, or make zip's receiver an array of nils of the same length. The latter approach can be implemented as follows:
vals = current_hash.values
#=> [["k", "r"], ["e", " ", "l"], ["d", "o", "w"], ["e", "h"]]
([nil]*vals.map(&:size).max).zip(*vals).flatten.compact.join
#=> "keder ohlw"
Note:
a = [nil]*vals.map(&:size).max
#=> [nil, nil, nil]
and
a.zip(*vals)
#=> [[nil, "k", "e", "d", "e"],
# [nil, "r", " ", "o", "h"],
# [nil, nil, "l", "w", nil]]
One could alternatively use Array#transpose rather than zip.
vals = current_hash.values
idx = (0..vals.map(&:size).max-1).to_a
#=> [0, 1, 2]
vals.map { |a| a.values_at(*idx) }.transpose.flatten.compact.join
#=> "keder ohlw"
See Array#values_at. Note:
a = vals.map { |a| a.values_at(*idx) }
#=> [["k", "r", nil],
# ["e", " ", "l"],
# ["d", "o", "w"],
# ["e", "h", nil]]
a.transpose
#=> [["k", "e", "d", "e"],
# ["r", " ", "o", "h"],
# [nil, "l", "w", nil]]

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}

Combining words in a string into anagrams using ruby

I wanted to make a program in which I would be able to sort and store the characters which are anagrams into individual groups. For ex for the string:
"scream cars for four scar creams" the answer should be:
[["scream", "creams"], ["cars", "scar"], ["for"], ["four"]]
For the above I used the code:
here = self.split()
there = here.group_by { |x| x.downcase.chars.sort}.values
And I got the required answer. But when I change the code to:
here = self.split()
there = here.group_by { |x| x.downcase.chars.sort}
I get the answer:
{["a", "c", "e", "m", "r", "s"]=>["scream", "creams"], ["a", "c", "r", "s"]=>["cars", "scar"], ["f", "o", "r"]=>["for"], ["f", "o", "r", "u"]=>["four"]}
I would like to know that why it is like this now? I got to the answer using hit-and-trial method.
As commented by Yevgeniy Anfilofyev , values is a method and hence it
Returns a new array populated with the values from hash
While, if we remove the method values then we get the whole hash and not only the array of values.

How to break down a string that's in an array even further

I'm trying to break down a sentence that's part of one string, but break it down into letters in their own array and have that inside one big array.
So what I mean is:
def break("hello world")
the code in the method would than result in this:
[["h","e","l","l","o], ["w","o","r","l","d"]]
The reason why I need it like that is so I can rearrange the letters in the order I want later. I've tried several things, but no luck.
"hello world".split.map &:chars
# => [["h", "e", "l", "l", "o"], ["w", "o", "r", "l", "d"]]
I wouldn't use break as a method name. It's a key word in the language.
def break_it(str)
str.split.map { |word| word.each_char.to_a }
end
break_it("hello world")

Is there a one liner to destructively use `.split(//)` (e.g. turn string into array)?

So far I have:
my_array = "Foo bar na nas"
my_array.delete!(" ").downcase!
my_array = my_array.split(//).uniq
To get:
==> ["f", "o", "b", "a", "r", "n", "s"]
I can't seem to use .split!(//) like .delete! or .downcase! but I want to do all of this in one step. Is it possible?
Using my_array.delete!(" ").downcase!.split!(//) yields "': undefined method 'split!' for nil:NilClass" so I assume .split! just doesn't exist.
No. If you will read documentation you will get that destructive methods return nil when there is nothing to change, so you cannot chain them. If you want to change string to array of it's letters excluding whitespces you should rathe run:
my_array = "Foo bar na nas".downcase.gsub(/\W/, '').split(//).uniq
There also don't exist destructive method split!. Just how can it exist? Ruby is strong-typed language so you cannot change String into Array because they aren't related.
my_array.downcase.gsub(' ','').chars.uniq
Why not use split with a regular expression matching white space or nothing?
"Foo bar na nas".downcase.split(/\s*/).uniq
This returns
["f", "o", "b", "a", "r", "n", "s"]
split! does not exist because by convention methods with ! alter the object itself in ruby, and you can not coerce a string into an array because ruby is strongly typed.
"Foo bar na nas".downcase.split(//).uniq.keep_if { |item| item != " " }
#=> ["f", "o", "b", "a", "r", "n", "s"]
"Foo bar na nas t p".downcase.split(//).uniq.keep_if { |item| item != " " }
#=> ["f", "o", "b", "a", "r", "n", "s", "t", "p"]

Resources