In queel, I can do:
User.where{id.eq "2" | admin.eq true}
to query. I want to know if I can trans [sic] a string, which is a condition like:
string = "id: 2"
or
string = "id.eq '2' | admin.eq true"
and run:
User.where{string}
or
User.where(string)
The result is not a hash. How can I do that?
What you need is hash and not string. You can use it like this,
hash = {id: 2}
User.where(hash)
And if you really want to use string you can do it like this,
string = "id = 2"
User.where(string)
If you want to execute the string you can use eval. In that case it will be like this,
string = "{id: 2}"
User.where(eval string)
NB to use the variant below, one should read first five pages of Google output on query “ruby eval is evil.”
User.where(instance_eval("{#{string}}"))
Related
I am receiving params like this "[[201], [511], [3451]]", I want to convert it into [201, 511, 3451]
Let's say params is what you're receiving, you can use scan and map to use a Regular Expression, look for the digits in the response and then map each item in the array to an integer:
params = "[[201], [511], [3451]]"
params_array = params.scan(/\d+/).map(&:to_i)
What we are doing here is we are looking through the string and selecting only the digits with the Scan method, afterwards we get a string array so to convert it into integers we use the Map method. As per the map method, thanks to Cary Swoveland for the update on it.
It will help you!
str_arr = "[[201], [511], [3451]]"
JSON.parse(str_arr).flatten
or
eval(str_arr).flatten
here is an interesting way (note that it only works in case your params is an array string)
arr1 = instance_eval("[1,2,3]")
puts arr1.inspect # [1,2,3]
arr2 = instance_eval("[[201], [511], [3451]]")
puts arr2.inspect # [[201], [511], [3451]]
First, I would make a sanity check that you don't get malevolent code injected:
raise "Can not convert #{params}" if /[^\[\]\d]/ =~ params
Now you can assert that your string is safe:
params.untaint
and then convert
arr = eval(params).flatten
or
arr = eval(params).flatten(1)
depending on what exactly you want to receive if you have deeply-nested "arrays" in your string.
I realize this is usually not a great practice, but how would I use a string containing an integer (e.g. "7") as a table key? For example:
local myTable = {
"1" = "Foo",
"2" = "Bar"
}
If memory serves from reading the Lua manual back in the day, that should be possible with some special syntax, but what I've written above is a syntax error.
Like this:
local myTable = {
["1"] = "Foo",
["2"] = "Bar"
}
Because the keys are not valid identifiers, you can't use the syntax sugar form.
Anyone tell me why this doesn't work?
GET_TABLE {1=ID}
key = string.format("%q", GET_TABLE[1])
RETURN_TABLE[key] = "ss"
print(RETURN_TABLE[ID])
print(GET_TABLE[1])
First print result: nil. Second print result: ID
I want the first print result to be: ss
GET_TABLE {1=ID}
key = "ID"
RETURN_TABLE[key] = "ss"
print(RETURN_TABLE[ID])
print(GET_TABLE[1])
The above works fine so I assume its due to the string.format not working right?
The %q format token returns the input as an escaped and quoted Lua string. This means that given the input ID it will return "ID" (the double quotes being part of the string!) which is a different string. (Or, represented as Lua strings, the input is 'ID' and the return value is '"ID"'.)
You have therefore set the ID key while trying to retrieve the "ID" key (which presumably does not exist).
> x = 'ID'
> =x
ID
> =string.format('%q', x)
"ID"
> =#x
2
> =#string.format('%q', x)
4
Your code does not compile (you need [] around the index), and you should use the raw string of ID, not the "quoted" string:
GET_TABLE = {[1]=ID}
key = string.format("%s", GET_TABLE[1])
Note that I had to initialize ID and RETURN_TABLE objects to the following:
ID = 'ID'
RETURN_TABLE = {}
Stylistic note: you should only use all-caps names for constants, otherwise too many makes code hard to read
By using Python we can redefine string into dictionary.
Example :
var = "testing"
var = {'body': var}
print var['body']
'testing'
With Lua I want to do same . I want to convert string object into table .
My try :
> var = "testing"
> var = {'body', var}
> print(var)
table: 0x12b2930
> for i,j in pairs(var) do
>> print(i)
>> print(j)
>> end
1
body
2
testing
>
With above example I can fetch testing string with
> print(var[2])
testing
>
Above code is not fulfilling my requirements. I want to store the value 'testing' with "body" key .
I want to fetch like below :
print(var['body'])
'testing'
Please help me on this
var = "testing"
var = {body = var}
print(var.body)
print(var["body"])
Comma in table construction separates table entries. So by specifying {"body", "testing"}, you create two entries with keys 1, 2 that are equal to "body" and "testing", respectively, since that is how you initialise a sequential array.
If you want to assign arbitrary keys to each value, you have to use =, as in {key1 = "body", key2 = "testing"}. Now you can access those elements in two ways. One is object like, using dot:
tab1.key1
And one is array/map like, using square brackets:
tab1["key1"].
In the second example, you have to pay attention to quotes. If you use double quotes, you're accessing a key directly. If not (tab1[key1]), you're using value stored in a variable named key1 as key specifier.
The Lua code closest to the Python code is
var = "testing"
var = {['body'] = var}
print(var['body'])
I am trying to compare an Variable to a value within a hash, but the hash can be queried using both Numeric and String arguments.
ED_CONTRIBUTIONS = {
1 => {
db_code: 1,
name: 'Provision of housing and transport',
abbreviation: 'Provisions',
group: 'Social development contributions'
}
}
I use a method like this to do the comparison:
def find_item(field, value)
value.downcase if value.is_a? String
applicable_items.find { |k,v| v[field] == value}.andand.last || {}
end
but sometimes the v[filed] is the db_code and as a result a digit. how can i make it so that if v[field] is a string that it be downcased? or rather how does one check the state of the value of a hash in such an instance.
You can check if it's a string like this v[field].kind_of? String, and downcase it if it is.
Or you can just v[field].to_s.downcase it without checking the variable type.
You can just parse it to a String:
value.to_s.downcase
and then you don't need to investigate if the value is a String