I have some data returned from an api which I've parsed down to this:
[{:a=>value1, :b=>value2, :c=>value3, :d=>value4}, {:a=>value5, :b=>value6, :c=>value7, :d=>value8},{:a=>value9, :b=>value10, :c=>value11, :d=>value12}, ...]
How can I create a new array of hashes with the keys AND values of b and c, given key = b and key = c? I want to pass the key and return the value and maintain the key. So I want to end up with:
[{:b=>value2, :c=>value3}, {:b=>value6, :c=>value7}, {:b=>value10, :c=>value11}, ...]
Pure ruby
array = [{:a=>'value1', :b=>'value2', :c=>'value3', :d=>'value4'}, {:a=>'value1', :b=>'value2', :c=>'value3', :d=>'value4'}]
b_and_c_array = array.map{|a| a.select{|k, _| [:b, :c].include?(k)} }
We take each hash using the map method that will return a result array. For each hash, we select only [:b, :c] keys. You can add more inside it.
Rails
If using Rails, let's use Hash#slice, prettier :
b_and_c_array = array.map{|a| a.slice(:b, :c) }
Related
I have an array
sample_array = [10001567, 10001789, 2347800, 10001534, 64786592, 00000355]
output_array = [10001567, 10001789, 10001534]
I need to fetch all the elements into a new array where the first 5 digits must be same in a given array. How to do this in ruby.
sample_array = [10001567, 10001789, 2347800, 10001534, 64786592]
patterns = sample_array.group_by { |el| el.to_s.chars.first(5).join.to_i }
=> {10001=>[10001567, 10001789, 10001534], 23478=>[2347800], 64786=>[64786592]}
UPDATE
Selecting the pattern for this specific case
patterns.select{|_,v| v.size > 1}.values.flatten
In the command
table.insert(table, data)
how can you use that but for the inserts have string keys?
PSEUDO CODE
tableOfStuff = {cat, pig, hat, lemon}
t = {}
for i=1, #tableOfStuff do
table.insert(t, key=tableOfStuff[i], data=tableOfStuff[i])
end
So I end up with a table...
t['cat'] == 'cat'
t['dog'] == 'dog'
etc.....
EDIT
I think my example confused people... I am asking how to use "insert.table" but insert tings with string keys...
table.insert(table,data,stringkey)
something like this?
Creating One Table
If all you want is to create a table with strings as keys, then check out Table Constructors, you have a couple options.
Option 1:
t = { key1 = "value1", key2 = "value2" }
--or like this:
t = { ["key1"] = "value1", ["key2"] = "value2" }
Option 2: (create an empty table first)
t = {}
t.key1 = "value1"
--or like this
t["key2"] = "value2"
It looks like you want the keys and values to be the same string and that is possible. Just write the same thing for key1 and value1. So t["cat"] = "cat".
Using Two Tables
Based on your example code, it looks like you want to take an existing table of strings and create from that a new table with strings as both the keys and the values. To do that:
table1 = { "cat", "pig", "hat", "lemon" }
table2 = {}
for i=1, #table1 do
table2[ table1[i] ] = table1[i]
end
--test
print table2["cat"]
Here is a good lesson about tables in Lua: Lua Tables Tutorial
The comment is right.You needn't and you can't use table.insert.You can see the document table.insert.It's only support the number.It' used for the array part of table.But you're using the hash part of a table.
code:
tableOfStuff = {"cat", "pig", "hat", "lemon"}
t = {}
for i=1, #tableOfStuff do
local szKey = tableOfStuff[i];
t[szKey] = tableOfStuff[i]; -- the value can be the others.
end
This question already has answers here:
How to iterate through a table in its exact order?
(4 answers)
Closed 7 years ago.
I need to iterate through Lua dictionary in the order that it's created.
For example:
t = {
['some'] = 'xxx',
['random'] = 'xxx',
['data'] = 'xxx',
['in'] = 'xxx',
['table'] = 'xxx',
}
Normal iterating with pairs gives a random sequence order:
for key, val in pairs(t) do
print(key.." : "..val)
end
random : xxx
some : xxx
data : xxx
table : xxx
in : xxx
I need:
some : xxx
random : xxx
data : xxx
in : xxx
table : xxx
EDIT: Changed the answer, the old one is below for reference
-- function definition
function addNewItem(keyTable, myTable, key, value)
table.insert(keyTable, key)
myTable[key] = value
end
To add a new pair into the table:
-- you may need to reset keyTable and myTable before using them
keyTable = { }
myTable = { }
-- to add a new item
addNewItem(keyTable, myTable, "key", "value")
Then, to iterate in the order the keys were added:
for _, k in ipairs(keyTable) do
print(k, myTable[k])
end
OLD ANSWER
Are you the one creating the table (Lua calls these tables and not dictionaries)?? If so, you could try something like the following:
-- tmp is a secondary table
function addNew(A, B, key, value)
table.insert(A, key)
B[key] = value
end
-- then, to browse the pairs
for _,key in ipairs(table) do
print(key, B[key])
done
The idea is that you use two tables. One holds the 'keys' you add (A) and the other (B) the actual values. They look like this:
Since A pairs the keys in a manner like
1 - key1
2 - key2
...
Then ipairs(A) will always return the keys in the order you added them. Then
use these keys to access the data
data = B[key1]
In Ruby, I have an array of hashes and an array. In my array of hashes, I want to replace the values in one of the key-value pairs with the values from my second array. What is the cleanest way to accomplish this?
Example (I want to replace the value of "total" with the values from my second array):
Array of hashes:
[{"date":"2012-05-27","total":1},{"date":"2012-05-28","total":9}]
Array:
[1, 10]
Desired Array of hashes:
[{"date":"2012-05-27","total":1},{"date":"2012-05-28","total":10}]
array.each_with_index {|e,i| hash_array[i]["total"] = e}
hashes = [{date: "2012-05-27", total: 1},{date: "2012-05-28", total: 9}] #unquoted keys
values = [1,10]
hashes.zip(values){|h,v| h[:total] = v}
p hashes #=>[{:date=>"2012-05-27", :total=>1}, {:date=>"2012-05-28", :total=>10}]
In Lua, you can create a table the following way :
local t = { 1, 2, 3, 4, 5 }
However, I want to create an associative table, I have to do it the following way :
local t = {}
t['foo'] = 1
t['bar'] = 2
The following gives an error :
local t = { 'foo' = 1, 'bar' = 2 }
Is there a way to do it similarly to my first code snippet ?
The correct way to write this is either
local t = { foo = 1, bar = 2}
Or, if the keys in your table are not legal identifiers:
local t = { ["one key"] = 1, ["another key"] = 2}
i belive it works a bit better and understandable if you look at it like this
local tablename = {["key"]="value",
["key1"]="value",
...}
finding a result with : tablename.key=value
Tables as dictionaries
Tables can also be used to store information which is not indexed
numerically, or sequentially, as with arrays. These storage types are
sometimes called dictionaries, associative arrays, hashes, or mapping
types. We'll use the term dictionary where an element pair has a key
and a value. The key is used to set and retrieve a value associated
with it. Note that just like arrays we can use the table[key] = value
format to insert elements into the table. A key need not be a number,
it can be a string, or for that matter, nearly any other Lua object
(except for nil or 0/0). Let's construct a table with some key-value
pairs in it:
> t = { apple="green", orange="orange", banana="yellow" }
> for k,v in pairs(t) do print(k,v) end
apple green
orange orange
banana yellow
from : http://lua-users.org/wiki/TablesTutorial
To initialize associative array which has string keys matched by string values, you should use
local petFamilies = {["Bat"]="Cunning",["Bear"]="Tenacity"};
but not
local petFamilies = {["Bat"]=["Cunning"],["Bear"]=["Tenacity"]};