Remove brackets which exists in array - ruby-on-rails

I do have an array which looks like:
["[0, 1]", "0", "1"]
The question is how to remove brackets inside the array, so the result which I wish to get would be:
["0", "1", "0", "1"]
Currently, I'm out of idea...

Depending on the specific structure of the array elements, you might be able to scan the elements for things that look like numbers and then use flat_map to unroll the arrays you get from scan:
['[0, 1]', '0', '1'].flat_map { |e| e.scan(/\d+/) }
# ["0", "1", "0", "1"]

This is what I came up with:
["[0, 1]", "0", "1"].to_s.split(/\W/).reject(&:blank?)

If the array elements might be nested, then I would go straight to YAML or JSON parsers:
require 'json'
['[0, [1, 0], 1]', '0', '1'].flat_map { |s| JSON.parse(s) }
# => [0, [1, 0], 1, 0, 1]

Related

Filter Array in Ruby on Rails with only to_s elements

I have this code that works well
def self.select_some_elements(some_value)
return elements.select { |element| element.some_value > some_value}
end
This code returns an array of elements class instances/objects. However, I would like to return the array of element.to_s instances/propeties, not the whole class objects, just strings/string properties
Is there a quick way to do it without going extra steps?
Introduction:
So, what you have achieved is a set (array in this case) of objects, which is great. What you have to do now is to transform this set into a different one: namely, replace each object with what that object's method to_s returns. There's a perfect method for that, called map. It goes through all the items, calls a block with each item as an argument and puts in the resulting array what the block has returned:
Open irb console and play around:
>> [1,2,3].map{|x| 1}
=> [1, 1, 1]
>> [1,2,3].map{|x| x+1}
=> [2, 3, 4]
>> [1,2,3].map{|x| "a"}
=> ["a", "a", "a"]
>> [1,2,3].map{|x| x.to_s}
=> ["1", "2", "3"]
>> [1,2,3].map(&:to_s)
=> ["1", "2", "3"]
The last transformation seems to be what you need:
The answer:
Add .map(&:to_s) at the end like this
def self.select_some_elements(some_value)
return elements.select { |element| element.some_value > some_value}.map(&:to_s)
end
.map(&:to_s) is a short version of .map { |element| element.to_s }. And you can read about Arra3#map in the docs
And when you wrap your head around the #map, check out Stefan's answer which shows how select{}.map can be "compressed" into one filter_map call (doing both things: filter, and mapping in one iteration over the set instead of two).
Starting with Ruby 2.7 there's filter_map:
elements = [1, 2, 3, 4, 5]
elements.filter_map { |e| e.to_s if e > 2 }
#=> ["3", "4", "5"]

How to change hash key from array of hashes in ruby?

Given:
data = [
{"votable_id"=>1150, "user_ids"=>"1,2,3,4,5,6,"},
{"votable_id"=>1151, "user_ids"=>"55,66,34,23,56,7,8"}
]
This is the expected result. Array should have first 5 elements.
data = [
{"votable_id"=>1150, "user_ids"=>["1","2","3","4","5"]},
{"votable_id"=>1151, "user_ids"=>["55","66","34","23","56","7",8"]}
]
This is what I tried :
data.map{|x| x['user_ids'] = x['user_ids'].split(',').first(5)}
Any other optimized solution ?
You can also use .map and .tap like this
data.map do |h|
h.tap { |m_h| m_h["user_ids"]= m_h["user_ids"].split(',').first(5)}
end
data = [
{"votable_id"=>1150, "user_ids"=>"1,2,3,4,5,6,"},
{"votable_id"=>1151, "user_ids"=>"55,66,34,23,56,7,8"}
]
Code
h=data.map do |h|
h["user_ids"]=[h["user_ids"].split(',').first(5)].flatten
h
end
p h
Output
[{"votable_id"=>1150, "user_ids"=>["1", "2", "3", "4", "5"]}, {"votable_id"=>1151, "user_ids"=>["55", "66", "34", "23", "56"]}]
data.map { |h| h.merge("user_ids"=>h["user_ids"].split(',').first(5)) }
#=> [{"votable_id"=>1150, "user_ids"=>["1", "2", "3", "4", "5"]},
# {"votable_id"=>1151, "user_ids"=>["55", "66", "34", "23", "56"]}]
See Hash#merge. This leaves data unchanged. To modify (or mutate) data use Hash#merge! (aka update). h.merge(k=>v) is a shortcut for h.merge({ k=>v }).

Rails, delete string-quotes from array, without turning it to a string

I have a method, that takes an array as argument, such as:
a = ["title", "item"]
I need to get rid of the " but I have difficulties to do so.
My goal is to achieve the following:
a = [title, item]
Two possible solutions were presented here:Getting rid of double quotes inside array without turing array into a string
eval x.to_s.gsub('"', '')
# => [1, 2, 3, :*, :+, 4, 5, :-, :/]
and
x=["1", "2", "3", ":*", ":+", "4", "5", ":-", ":/"]
=> ["1", "2", "3", ":*", ":+", "4", "5", ":-", ":/"]
x.map{|n|eval n}
=> [1, 2, 3, :*, :+, 4, 5, :-, :/]
I tried both of these solutions, but It always leads to this error:
undefined local variable or method `title'
How do I get rid off these " quotes in an array?
Edit:
I need to alter an array. This is what I am trying to do:
a = ["title", "item"]
should change to something like:
a = [model_class.human_attribute_name(:title), model_class.human_attribute_name(:title)]
(It's about translations).
This code is in a model.rb, maybe that helps.Here is my full code:
def humanifier(to_translate_array)
translated = []
to_translate_array.each do |element|
translated.push("model_class.human_attribute_name(:#{element})")
end
return translated
end
It looks like you want to translate strings into symbols, you can do that with #to_sym
to_translate_array.each do |element|
translated.push("model_class.human_attribute_name(#{element.to_sym})")
end
Or if you actually want the translated value, (and not just a string "model_class.human...")
to_translate_array.each do |element|
translated.push(model_class.human_attribute_name(element.to_sym))
end
"title" is a string, :title is a symbol.

Remove duplicates from an array of array

How do I remove duplicates from this array?
product_areas = [["1", "2", "3"], ["3", "1", "2"]]
I have tried product_areas.uniq!, product_area.uniq but the same thing is repeating. What am I missing here?
Expected Output:
product_areas = ["1", "2", "3"]
Try this:
product_areas = [["1", "2", "3"], ["3", "1", "2"]].flatten.uniq
Using flatten on your array will create the following result:
["1", "2", "3", "3", "1", "2"]
When you call uniq on that array, you will get the result you were expecting:
["1", "2", "3"]
As previously pointed out
product_areas = [["1", "2", "3"], ["3", "1", "2"]].flatten.uniq
-OR-
product_areas.flatten.uniq!
will both lead you to your desired answer.
Why?
When you were running "product_areas.uniq!" the process was comparing the two inner arrays against each other, other than the elements of each array. Because both ["1", "2", "3"] and ["3", "1", "2"] are unique in the array, neither will be removed. As an example say you had the following array
product_areas = [["1", "2", "3"], ["3", "1", "2"], ["1","2","3"]]
and you ran:
product_areas = product_areas.uniq
product_areas would then look like the following:
product_areas = [["1", "2", "3"], ["3", "1", "2"]]
What you need to be aware of when running any sort of enumerable method on arrays is it will only move down to each individual element. So if inside an array you have more arrays, any iterative method will look at the inner array as a whole. Some sample code to demonstrate this:
array_of_arrays = [[1,2,3], [4,5,6]]
array_of_arrays.each do |array|
p array
end
#---OUPUT---
# [1, 2, 3]
# [4, 5, 6]
array_of_arrays.each do |array|
array.each do |element|
p element
end
end
#---OUPUT---
# 1
# 2
# 3
# 4
# 5
# 6
I've used this little snippet of code over and over again in my career as a Ruby on Rails developer to solve this frequently encountered problem in a single piece of neat little code. The end result of this code is that you can just call something like
product_areas.squish
to do the following:
flatten 2-D arrays into 1-D arrays
remove nil elements
remove duplicate elements
I do this by adding an initializer config/initializer/core_ext.rb to my project which extends the core Ruby functionality as follows:
class Array
def squish
blank? ? [] : flatten.compact.uniq
end
end
class NilClass
def squish
[]
end
end

reading array of params in RoR

If I have URL something like below:
http://test.com?x=1&x=2&x=3&x=4&x=5&x=6&x=7
Then how can I read all "x" values?
Added new comment: Thanks for all your answers. I am basically from Java and .Net background and recently started looking Ruby and Rails. Like in Java, don't we have something similar as request.getParameterValues("x");
You should use following url instead of yours:
http://test.com?x[]=1&x[]=2
and then you'll get these params as array:
p params[:x] # => ["1", "2"]
IF IT IS A STRING, but not a http request
Do this:
url = 'http://test.com?x=1&x=2&x=3&x=4&x=5&x=6&x=7'
p url.split(/(?:\A.*?|&)x=/).drop(1)
If you want to convert them to integers, do:
p url.split(/(?:\A.*?|&)x=/).drop(1).map(&:to_i) (ruby 1.9)
or
p url.split(/(?:\A.*?|&)x=/).drop(1).map{|v| v.to_i}
IF IT IS A STRING, but not a http request I even didn't imagine if author don't know how to handle params of request url...
url = "http://test.com?x=1&x=2&x=3&x=4&x=5&x=6&x=7"
vars = url.scan(/[^?](x)=([^&]*)/)
#=> [["x", "2"], ["x", "3"], ["x", "4"], ["x", "5"], ["x", "6"], ["x", "7"]]
x = vars.map{|a| a[1]}
#=> ["2", "3", "4", "5", "6", "7"]
x.map!(&:to_i)
#=> [2, 3, 4, 5, 6, 7]
Or if you need to extract valuse only:
vars = url.scan(/[^?]x=([^&]*)/).flatten
#=> ["2", "3", "4", "5", "6", "7"]
vars = url.scan(/[^?]x=([^&]*)/).flatten.map(&:to_i)
#=> [2, 3, 4, 5, 6, 7]

Resources