Is there a map function in Ruby? [duplicate] - ruby

This question already has answers here:
What does the "map" method do in Ruby?
(8 answers)
Closed 9 months ago.
I want to map values from a named list in Ruby. Is there an equivalent map function in Ruby? I have an array
letters = ['a', 'b', 'c', 'd']
capital = letters .map { l, l .capitalize] }
puts capital

Yes, Ruby arrays have a .map method that you can call (https://ruby-doc.org/core-2.7.5/Array.html#method-i-map).
What you probably want is:
letters = ['a', 'b', 'c', 'd']
capitals = letters.map {|letter| letter.capitalize}
or you could also use the shorter form:
letters = ['a', 'b', 'c', 'd']
capitals = letters.map(&:capitalize)
or maybe even use the .upcase instead of .capitalize if all you need for the result is uppercase.

Related

How to test for an element in an array of arrays with chai and mocha?

I have an array with arrays nested in it. I tried to test it with Chai, but it doesn't pass the test. I have checked that the value in both of these arrays are correct.
const mainArray = [
['f', 'r', 'e', 'e'], ['b', 'e', 'e']
]
const targetArray = ['b', 'e', 'e']
expect(mainArray).to.include(targetArray) //False, expect it to be True
How can I test this correctly?
You can use .deep.members
chai.expect(mainArray).to.include.deep.members([targetArray])
When doing .to.include(targetArray), its looking in the mainArray to have the members in targetArray. So its looking for b, e inside mainArray

Elasticsearch search from array content

Let say I have following 3 documents in ES index.
{
someId: 'A'
}
{
someId: 'B'
}
{
someId: 'C'
}
Let's say I have an array of someId ['A', 'B', 'C', 'D', 'E']. What I need to find is which of elements in the array is in ES.
For the above example ES contains document for someId ['A', 'B', 'C'] but not for ['D', 'E']
Is there an ES query to achieve it?

Ruby string/array combinations preserving order

I want to find all the combinations of a string preserving the order . Is there any built in method in Ruby to achieve this?
For example, "abcd".all_combinations should give the output:
a
b
c
d
ab
bc
cd
abc
bcd
abcd
Probably not the ideal implementation, but this works:
def combinations(str)
items = str.chars
(1..items.length).map { |i| items.each_cons(i).map(&:join) }.flatten
end
Also check Enumerable#each_cons. You can also just add it to the String class like this:
class String
def combinations
items = self.chars
(1..items.length).map { |i| items.each_cons(i).map(&:join) }.flatten
end
end
'abcd'.combinations
What is happening:
We make the string an actual array of characters with String#chars.
Then for each number i between 1 to the length of the string:
Call Enumerable#each_cons which basically returns the possible combinations of the length i as an array of characters too. So if i is 2, then the result of items.each_cons(2) will be [ ['a', 'b'], ['b', 'c'], ['c', 'd'] ]
The .map(&:join) part is basically calling Array#join on each of the elements of that array of arrays, so it becomes ['ab', 'bc', 'cd']
The result of (1..items.length).map { |i| items.each_cons(i).map(&:join) } is: [ ['a', 'b', 'c', 'd'], ['ab', 'bc', 'cd'], ['abc', 'bcd'], ['abcd'] ] which is an array of arrays. We call Array#flatten on it to make it a simple array (read the flatten link for more).
There is no builtin function that does exactly what you're looking for.
String#each_cons looks interesting as Tamer points out.
Here's an alternate solution:
def all_combos(str)
1.upto(str.length) do |segment_length|
0.upto(str.length - segment_length) do |starting_point|
puts str[starting_point, segment_length]
end
end
end
all_combos("abcd")
The starting and ending indices of the sub-strings form a pattern of a combination with repetition, for which Ruby does have a built-in method.
class String
def all_combinations
idx = (0 ... self.size).to_a
idx.repeated_combination(2){|i,j| yield self[i..j]}
end
end
"abcd".all_combinations{|combo| puts combo}

Create hash with keys from array and a standard value

I have an array like this:
['a', 'b', 'c']
What is the simplest way to turn it into:
{'a' => true, 'b' => true, 'c' => true}
true is just a standard value that values should hold.
How about below ?
2.1.0 :001 > ['a', 'b', 'c'].each_with_object(true).to_h
=> {"a"=>true, "b"=>true, "c"=>true}
Try:
Hash[ary.map {|k| [k, true]}]
Since Ruby 2.0 you can use to_h method:
ary.map {|k| [k, true]}.to_h
Depending on your specific needs, maybe you do not actually need to initialize the values. You could simply create a Hash with a default value of true this way:
h = Hash.new(true)
#=> {}
Then, when you try to access a key that was not present before:
h['a']
#=> true
h['b']
#=> true
Pros: less memory used, faster to initialize.
Cons: does not actually store keys so the hash will be empty until some other code stores values in it. This will only be a problem if your program relies on reading the keys from the hash or wants to iterate over the hash.
['a', 'b', 'c'].each_with_object({}) { |key, hash| hash[key] = true }
Another one
> Hash[arr.zip Array.new(arr.size, true)]
# => {"a"=>true, "b"=>true, "c"=>true}
You can also use Array#product:
['a', 'b', 'c'].product([true]).to_h
#=> {"a"=>true, "b"=>true, "c"=>true}
Following code will do this:
hash = {}
['a', 'b', 'c'].each{|i| hash[i] = true}
Hope this helps :)
If you switch to Python, it's this easy:
>>> l = ['a', 'b', 'c']
>>> d = dict.fromkeys(l, True)
>>> d
{'a': True, 'c': True, 'b': True}

Convert array to nested hash in ruby [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have following array
['a', 'b', 'c']
How to convert it to hash like this bellow:
{'a' => { position: index of array element a }, 'b' ...., 'c' ... }
Best regards
Georgi.
First you could create an array like the following using the methods Array#map and Enumerator#with_index:
ary = ['a', 'b', 'c']
temporary = ary.map.with_index { |e, i| [e, { position: i }] }
# => [["a", {:position=>0}], ["b", {:position=>1}], ["c", {:position=>2}]]
Then you can convert the resulting array to hash using the Array#to_h method available since Ruby 2.1:
temporary.to_h
# => {"a"=>{:position=>0}, "b"=>{:position=>1}, "c"=>{:position=>2}}
For older versions of Ruby, the Hash.[] method will do:
Hash[temporary]
# => {"a"=>{:position=>0}, "b"=>{:position=>1}, "c"=>{:position=>2}}
['a', 'b', 'c'].each_with_index.reduce({}) do |s, (e, i)|
s[e] = { position: i }
s
end

Resources