In a .rb file I am using result = JSON.parse(res.body)['data']['results'] and get
[
{"suggestion":"Lineman","id":"49.10526"},
{"suggestion":"Linguist","id":"27.10195"},
{"suggestion":"Librarian","id":"25.47"},
{"suggestion":"Lifeguard","id":"33.39"},
{"suggestion":"Line Cook","id":"35.30125"},
{"suggestion":"Life Coach","id":"21.209"},
{"suggestion":"Life Guard","id":"33.1001"}
]
now I want an array like
[
"Lineman",
"Linguist",
"Librarian",
"Lifeguard",
"Line Cook",
"Life Coach",
"Life Guard"
]
What should I apply to JSON.parse(res.body)['data']['results']?
You can use Enumerable#map:
other_result = result.map { |val| val['suggestion'] }
it returns a new array with results of applying the block to initial array elements
Try this:
suggestions = result.pluck(:suggestion)
# ["Lineman", "Linguist", "Librarian", "Lifeguard", "Line Cook", "Life Coach", "Life Guard"]
This plucks all the suggestion values and returns them as an array.
Related
I have an array as
["first_name"]
and I want to convert it to
["user.first_name"]
I cannot figure out how I can do this in rails.
If you would like to append text to the values you have in a array you're going to probably want to loop through the data and append to each element in the array like so:
my_array = ["test", "test2", "first_name"]
new_array = my_array.collect{|value| "user.#{value}" }
new_array will now be:
["user.test", "user.test2", "user.first_name"]
You could also just overwrite your original array by using collect! like so
my_array = ["test", "test2", "first_name"]
my_array.collect!{|value| "user.#{value}" }
This will of course overwrite your original original data in my_array
If you would like to just change one value in the array you could use the index of that array and assign the value
my_array = ["test", "test2", "first_name"]
my_array[1] = "user.#{my_array[1]}}
my_array will now read:
["test", "user.test2", "first_name"]
Supposing you've multiple elements in your array, I recommend using .map.
It allows you to iterate the array elements, and return a new value for each of them.
%w[first_name last_name email].map do |attr|
"user.#{attr}"
end
# => [user.first_name, user.last_name, user.email]
I've an array contains hashes, I want to filter few parameters from the hash and insert the filtered data in another array but am not succeed below is the sample data I've used
a = Array.new
a = [
{"name"=>"hello", "age"=>"12", "sex"=> "M", "city"=>"Chennai"},
{"name"=>"name2", "age"=>"26", "sex"=> "M", "city"=>"Banglore"}
]
line_item = Array.new
hash_data = {}
a.each do |datas|
hash_data[:name] = datas["name"]
hash_data[:age] = datas["age"]
line_item << hash_data
end
I am getting this result:
[
{:name=>"name2", :age=>"26"},
{:name=>"name2", :age=>"26"}
]
But am expecting this:
[
{:name=>"hello", :age=>"12"},
{:name=>"name2", :age=>"26"}
]
Somebody please help to sort out this, Thanks in advance
Defining the hash outside the loop means that you keep adding the same hash object again (while overwriting its previous values). Instead, create a fresh hash within the loop:
line_items = []
a.each do |datas|
hash_data = {}
hash_data[:name] = datas["name"]
hash_data[:age] = datas["age"]
line_items << hash_data
end
The code looks a bit unidiomatic. Let's refactor it.
We can set the keys right within the hash literal:
line_items = []
a.each do |datas|
hash_data = { name: datas["name"], age: datas["age"] }
line_items << hash_data
end
We can get rid of the hash_data variable:
line_items = []
a.each do |datas|
line_items << { name: datas["name"], age: datas["age"] }
end
And we can use map to directly transform the array:
line_items = a.map { |h| { name: h["name"], age: h["age"] } }
#=> [{:name=>"hello", :age=>"12"}, {:name=>"name2", :age=>"26"}]
You can get the expected result with a combination of map and slice
a = [
{"name"=>"hello", "age"=>"12", "sex"=> "M", "city"=>"Chennai"},
{"name"=>"name2", "age"=>"26", "sex"=> "M", "city"=>"Banglore"}
]
a.map{ |e| e.slice("name", "age") }
#=> [{"name"=>"hello", "age"=>"12"}, {"name"=>"name2", "age"=>"26"}]
map: Returns Array containing the values returned by block
slice: Returns Hash including only the specified keys
In your loop you are essentially populating line_item with hash_data twice. This is the same object however. You can remedy this by using .dup.
a.each do |datas|
hash_data[:name]=datas["name"]
hash_data[:age]=datas["age"]
line_item << hash_data.dup # <- here
end
irb(main):044:0> line_item
=> [{:name=>"hello", :age=>"12"}, {:name=>"name2", :age=>"26"}]
Edit: I prefer rado's suggestion of moving your definition of hash_data inside the loop over using .dup. It solves the problem more than treating the symptom.
I think a lot of people are over complicating this.
You can achieve this using the following:
a.map { |hash| hash.select { |key, _value| key == 'name' || key == 'age' } }
If you want to return an array, you should nearly always be using map, and select simply selects the key - value pairs that match the criteria.
If you're set on having symbols as the keys, you can call symbolize_keys on the result.
I'll expand the code so it's a little more readable, but the one liner above works perfectly:
a.map do |hash|
hash.select do |key, _value|
key == 'name' || key == 'age'
end
end
On the first line hash_data[:name]=datas["name"] you are setting the key of the hash. That's why when the loop iterate again, it is overriding the value and after that push the new result to the hash.
One solution with reusing this code is just to put the hash_data = {} on the first line of your loop. This way you will have a brand new hash to work with on every iteration.
Also I would recommend you to read the docs about the Hash module. You will find more useful methods there.
If you want for all keys you can do this
array = [{"name"=>"hello", "age"=>"12", "sex"=> "M", "city"=>"Chennai"}, {"name"=>"name2", "age"=>"26""sex"=> "M", "city"=>"Banglore"}]
new_array = array.map{|b| b.inject({}){|array_obj,(k,v)| array_obj[k.to_sym] = v; array_obj}}
Ref: inject
Happy Coding
I have a multi-dimensional array that contains a lot of information about various objects. I'm looking to remove all but the first instance of arrays that contain similar information:
multi_array = [
["Nissan", "Altima", "tan", "2016", "80000"],
["Ford", "F-150", "silver", "2012", "120000"],
["Nissan", "Altima", "red", "2009", "50000"],
["Audi", "A4", "blue", "2014", "30000"]
]
In the above example I want to remove any of the subarrays that have the instance of "Altima" in it so that result would be:
fixed_multi_array = [
["Nissan", "Altima", "tan", "2016", "80000"],
["Ford", "F-150", "silver", "2012", "120000"],
["Audi", "A4", "blue", "2014", "30000"]
]
What's the fastest way to do this in ruby (or Ruby on Rails)?
Update:
Should have clarified, I'm looking to de-duplicate based on a value that's always in the same position of the sub-arrays. So, in example above I'm always looking to de-dupe only on value in position 1 of the sub-arrays.
You can use uniq:
fixed_multi_array = multi_array.uniq{|x| x[1]}
Demonstration
Here is one more way to do this:
multi_array.group_by {|i| i[1]}.values.map(&:first)
I have included the given code:
#classes = {1=>"USA", 3=>"France", 2=>"UK", 5=>"Europe", 7=>"Delhi", 8=>"test"}
#amaze = params[:test] #I get "1,3,7"
I get this, now please guide me how to match keys with #amaze and accordingly fetch its values from #classes i.e USA, France, Delhi.
Since #amaze is just a String, lets first convert it in Array so its easy to enumerate:
#amaze = "1,3,7"
#amaze = #amaze.split(",")
# => ["1", "3", "7"]
Now, since you have all keys extract all values:
#amaze.map { |i| #classes[i.to_i] }
# => ["USA", "France", "Delhi"]
Split #amaze by , and get an array of keys, convert them into Integer, then select only those key/value pairs which key is into this array of keys. Something like this:
#classes = {1=>"USA", 3=>"France", 2=>"UK", 5=>"Europe", 7=>"Delhi", 8=>"test"}
#amaze = "1,3,7" #I get "1,3,7"
arr = #amaze.split(',').map(&:to_i)
p #classes.select{|el| arr.include? el}
Result:
#> {1=>"USA", 3=>"France", 7=>"Delhi"}
If you want values only use .values:
p #classes.select{|el| arr.include? el}.values
Result:
#> ["USA", "France", "Delhi"]
For what(seemingly) you are asking, the below line will do it:
#amaze.split(",").each { |i| p #classes[i.to_i] }
# If #amaza = "1,3,7", above line will output:
# => "USA"
# "France"
# "UK"
This should work well for you:
#classes = {1=>"USA", 3=>"France", 2=>"UK", 5=>"Europe", 7=>"Delhi", 8=>"test"}
#amaze = params[:test].split(",").map(&:to_i)
#classes.values_at(*#amaze)
#=> ["USA", "France", "Delhi"]
Hash#values_at accepts an indefinite number of keys and returns their values as an array. The * (splat) operator explodes the array so this call actually becomes #classes.values_at(1,3,7) Docs
Might also want to add a compact to the end in the event a key does not exist. e.g
#amaze = params[:test].split(",").map(&:to_i) # Asssume this returns [1,3,7,9]
#classes.values_at(*#amaze)
#=> ["USA", "France", "Delhi",nil]
#classes.values_at(*#amaze).compact
#=> ["USA", "France", "Delhi"]
I think a clearer understanding of hashes would help you out here.
A Hash is a data structure that is a list of key-value pairs. For example, the following is a Hash object of key-value pairs (your example):
#classes = {1=>"USA", 3=>"France", 2=>"UK", 5=>"Europe", 7=>"Delhi", 8=>"test"}
If you want to extract a value from #classes, you need to pass the key of the value you want. If we wanted "USA" we would pass the key of 1 to #classes. If we wanted "France", we would pass it the key of 3:
#classes[1] would return "USA" and #classes[3] would return "France".
It's not clear what data structure #amaze is according to your question, but let's say it's the string "1, 3, 7" which we can split to create an array [1, 3, 7].
You could iterate over the array to get each of the values from #classes:
#amaze.split(",").map(&:to_i).each do |key|
puts #classes[key]
end
That would print out each of the corresponding values to keys in #classes.
I got two JSON that are structured like this. First one comes from an API:
[
{
"course_code":"Basic 101 - 0913",
"name":"Basic 101",
"start_at":"2013-09-16T00:00:00+02:00",
"end_at":"2013-10-13T23:55:00+02:00",
"workflow_state":"available"
},
{"course_code":"Medium 201 - 0913",
"name":"Medium 201",
"start_at":"2013-08-06T16:55:25+02:00",
"end_at":null,
"workflow_state":"available"
}
]
The second one is a JSON export from my database:
[
{
"id":1,
"course_id":"Basic 101",
"name":"Basic Level",
"description":"blablabla",
"discipline_id":"1",
"duration":"28",
"created_at":null,
"updated_at":null
},
{
"id":2,
"course_id":"Medium 201",
"name":"Medium Level",
"description":"blablabla",
"discipline_id":"1",
"duration":"28",
"created_at":null,
"updated_at":null
}
]
I would like to merge these two JSON into one, with matched :name in the first JSON and :course_id in the second one.
If you know good tutorials on using JSON in Rails, I'm really interested.
This isn't really a JSON issue.
When parsing JSON data it returns arrays and hashes.
One way of merging it in this case would be to loop through the data and check for the parameters you want/need to match. Once you find a match you can either manually create a new Hash with the needed data or you could use
hash1.merge(hash2)
http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-merge
which would return a hash consisting of both Hashes - attributes with the same name would be overwritten in the first hash.
Just a quick answer, to let you know where to go. Assuming first json is in json1 and second is in json2 variables, this code:
require 'json'
arr1 = JSON.parse(json1)
arr2 = JSON.parse(json2)
mrg = []
arr1.each do |el1|
arr2.each do |el2|
if el2['course_id'] == el1['name']
mrg.push(el1.merge(el2))
end
end
end
p mrg
Will print:
[
{
"course_code"=>"Basic 101 - 0913",
"name"=>"Basic Level",
"start_at"=>"2013-09-16T00:00:00+02:00",
"end_at"=>"2013-10-13T23:55:00+02:00",
"workflow_state"=>"available",
"id"=>1,
"course_id"=>"Basic 101",
"description"=>"blablabla",
"discipline_id"=>"1",
"duration"=>"28",
"created_at"=>nil,
"updated_at"=>nil
},
{
"course_code"=>"Medium 201 - 0913",
"name"=>"Medium Level",
"start_at"=>"2013-08-06T16:55:25+02:00",
"end_at"=>nil,
"workflow_state"=>"available",
"id"=>2,
"course_id"=>"Medium 201",
"description"=>"blablabla",
"discipline_id"=>"1",
"duration"=>"28",
"created_at"=>nil,
"updated_at"=>nil
}
]