I have a string of values like this:
=> "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
I want to put each value in an array so I can use each do. So something like this:
#numbers =>["72", "58", "49", "62", "9", "13", "17", "63"]
This is the code I want to use once the string is a usable array:
#numbers.each do |n|
#answers << Answer.find(n)
end
I have tried using split() but the characters are not balanced on each side of the number. I also was trying to use a regex split(/\D/) but I think I am just getting worse ideas.
The controller:
#scores = []
#each_answer = []
#score.answer_ids.split('/').each do |a|
#each_answer << Answer.find(a).id
end
Where #score.answer_ids is:
=> "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
Looks like an array of JSON strings. You could probably use Ruby's built-in JSON library to parse it, then map the elements of the array to integers:
input = "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
require 'json'
ids = JSON.parse(input).map(&:to_i)
#answers += Answer.find(ids)
I'd use:
foo = "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
foo.scan(/\d+/) # => ["3", "4", "60", "71", "49", "62", "9", "14", "17", "63"]
If you want integers instead of strings:
foo.scan(/\d+/).map(&:to_i) # => [3, 4, 60, 71, 49, 62, 9, 14, 17, 63]
If the data originates inside your system, and isn't the result of user input from the wilds of the Internet, then you can do something simple like:
bar = eval(foo) # => ["3", "4", "60", "71", "49", "62", "9", "14", "17", "63"]
which will execute the contents of the string as if it was Ruby code. You do NOT want to do that if the input came from user input that you haven't scrubbed.
In your code n is a String, not an Integer. The #find method expects an Integer, so you need to convert the String to an Array of Integers before iterating over it. For example:
str = "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
str.scan(/\d+/).map(&:to_i).each do |n|
#answers << Answer.find(n)
end
Related
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 }).
I'm having an array:
arr =["112000666", "10", "111282637", "15", "111342625", "12", "112000674",
"11", "111488203", "18", "111237150", "20"]
Is there any way to make a 2D array and divided by 2 values? Something like this:
[["112000666", "10"], ["111282637", "15"], ["111342625", "12"],
["112000674", "11"], ["111488203", "18"], ["111237150", "20"]]
The number of elements will always be even.
For rails you can use in_groups_of method:
arr.in_groups_of(2)
#=> [["112000666", "10"], ["111282637", "15"], ["111342625", "12"],
# ["112000674", "11"], ["111488203", "18"], ["111237150", "20"]]
Pure Ruby:
arr.each_slice(2).to_a
#=> [["112000666", "10"], ["111282637", "15"], ["111342625", "12"],
# ["112000674", "11"], ["111488203", "18"], ["111237150", "20"]]
See Enumerable#each_slice.
I am getting the following arrays from external api endpoint.
Input:-
1. [["date", "country_name", "month"], ["2019-02-21", "US", "Jan"]]
2. ["name", "homeAddress", "zipcode"]
Expected Output:-
1. [["Date", "Country Name", "Month"], ["2019-02-21", "US", "Jan"]]
2. ["Name", "Home Address", "Zipcode"]
How can I change the each array in an efficient way in Ruby on Rails?
Update:
Some of the name are different in expected as follows
Input:
["column1", "column2", "date"]
Expected output:
["column3", "column4", "Date"]
How can I get the above output?
Answer:-
Inputs:-
a=['1', '2', '3', '4']
b= {"1"=>"10", "2"=>"20", "3"=>"30"}
Execute:
c=a.map{|i| b[i].nil?? i : b[i] }
Output:-
["10", "20", "30", "4"]
You want to replace '_' with space or bring space when capital letter is encountered within string,
Try following rails methods to do so,
"now_isTheTime".titleize.camelize
=> "Now Is The Time"
ar1 = [["date", "country_name", "month"], ["2019-02-21", "US", "Jan"]]
ar2 = ["name", "homeAddress", "zipcode"]
def formatter(string)
return string if string.length < 3 || string.count("0-9").positive?
string.titleize.camelize
end
ar1.map{ |sub_arr| sub_arr.map(&method(:formatter)) }
ar2.map(&method(:formatter))
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.
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