I have a variable (result) that looks like this when doing YAML::dump(result):
responseHeader:
status: 0
QTime: 1
params:
wt: ruby
q: enid:(15542697739)
response:
numFound: 1
start: 0
docs:
- enid: "15542697739"
I want to do a conditional comparison on the enid like this:
if result["response"]["docs"]["enid"].to_i == num['1']['car']
where num['1']['car'] is an integer.
Whenever I attempt this, I get a TypeError thrown,
can't convert String into Integer
(TypeError)
even if I attempt
result["response"]["docs"]["enid"].to_i
or
Integer(result["response"]["docs"]["enid"])
How do I get my enid value converted to an integer so I can make this comparison?
The problem is that what's in result["response"]["docs"] is NOT a hash and you're addressing it like one. What you need in this case is result["response"]["docs"][0]["enid"]. If you want to see why, try p result["response"] to see what Ruby data structures are being used at each level. YAML can be a little misleading here even if you've been reading it a while.
Related
I have to be honest that I don't quite understand Lua that well yet. I am trying to overwrite a local numeric value assigned to a set table address (is this the right term?).
The addresses are of the type:
project.models.stor1.inputs.T_in.default, project.models.stor2.inputs.T_in.default and so on with the stor number increasing.
I would like to do this in a for loop but cannot find the right expression to make the entire string be accepted by Lua as a table address (again, I hope this is the right term).
So far, I tried the following to concatenate the strings but without success in calling and then overwriting the value:
for k = 1,10,1 do
project.models.["stor"..k].inputs.T_in.default = 25
end
for k = 1,10,1 do
"project.models.stor"..j..".T_in.default" = 25
end
EDIT:
I think I found the solution as per https://www.lua.org/pil/2.5.html:
A common mistake for beginners is to confuse a.x with a[x]. The first form represents a["x"], that is, a table indexed by the string "x". The second form is a table indexed by the value of the variable x. See the difference:
for k = 1,10,1 do
project["models"]["stor"..k]["inputs"]["T_in"]["default"] = 25
end
You were almost close.
Lua supports this representation by providing a.name as syntactic sugar for a["name"].
Read more: https://www.lua.org/pil/2.5.html
You can use only one syntax in time.
Either tbl.key or tbl["key"].
The limitation of . is that you can only use constant strings in it (which are also valid variable names).
In square brackets [] you can evaluate runtime expressions.
Correct way to do it:
project.models["stor"..k].inputs.T_in.default = 25
The . in models.["stor"..k] is unnecessary and causes an error. The correct syntax is just models["stor"..k].
I have the following enum:
enum MyEnum {
case One
case Two
case Three
}
But when I print this line:
print("This is the hash value of One \(MyEnum.One.hashValue)")
I get the following output:
This is the hash value of One -7827947590157343570
if I re-run the code I get:
This is the hash value of One 7980945707037922449
Should I being getting something like this:
This is the hash value of One 0
My question for you guys why am I getting random numbers?
I'll really appreciate your help.
The answer to this question it is well documented hashValue
The short answer is that this is normal behaviour.
Hash values are not guaranteed to be equal across different executions
of your program. Do not save hash values to use during a future
execution
Should I being getting something like this?
This is the hash value of One 0
No. HashValue is different from RawValue. If you want your enumeration cases to have a rawValue starting at 0 you need to declare your enumeration type as Int. Btw note that it is Swift naming convention to name your enumeration cases starting with a lowercase letter:
enum TestEnum: Int {
case one
case two
case three
}
TestEnum.one.rawValue // 0
TestEnum.two.rawValue // 1
TestEnum.three.rawValue // 2
I am trying to use a YAML file, reading from it and writing to it a list of values. On the first run of this script, the yaml file is correctly created, but then on the second it throws a conversion TypeError which I don't know to fix.
db_yml = 'store.yml'
require 'psych'
begin
if File.exist?(db_yml)
yml = Psych.load_file(db_yml)
puts "done load"
yml['reminders']['reminder_a'] = [123,456]
yml['reminders']['reminder_b'] = [457,635,123]
File.write(db_yml, Psych.dump(yml) )
else
#the file does not exist yet, create an empty one.
File.write(db_yml, Psych.dump(
{'reminders' => [
{'reminder_a'=> [nil]},
{'reminder_b'=> [nil]}
]}
)) #Store
end
rescue IOError => msg
# display the system generated error message
puts msg
end
produces the file store.yml on first run:
---
reminders:
- reminder_a:
-
- reminder_b:
-
So far so good. But then on the second run it fails with
done load
yamlstore.rb:23:in `[]=': no implicit conversion of String into Integer (TypeError)
from yamlstore.rb:23:in `<main>'
Could you tell me where I am going wrong?
The error message says that you were passing a String where Ruby expects something that is implicitly convertible to an Integer. The number one place where Ruby expects something that is implicitly convertible to an Integer is when indexing into an Array. So, whenever you see this error message, you can be 99% sure that you are either indexing an Array with something you thought was an Integer but isn't, or that you are indexing an Array that you thought was something else (most likely a Hash). (The other possibility is that you are trying to do arithmetic with a mix of Integers and Strings.)
Just because Ruby is a dynamically-typed programming language does not mean that you don't need to care about types. In particular, YAML is a (somewhat) typed serialization format.
The type of the file you are creating looks something like this:
Map<String, Sequence<Map<String, Sequence<Int | null>>>>
However, you are accessing it, as if it were typed like this:
Map<String, Map<String, Sequence<Int | null>>>
To put it more concretely, you are creating the value corresponding to the key 'reminders' as a sequence (in YAML terms, an Array in Ruby terms) of maps (Hashes). Arrays are indexed by Integers.
You, however, are indexing it with a String, as if it were a Hash.
So, you either need to change how you access the values like this:
yml['reminders'][0]['reminder_a'] = [123, 456]
# ↑↑↑
yml['reminders'][1]['reminder_b'] = [457,635,123]
# ↑↑↑
Or change the way you initialize the file like this:
File.write(db_yml, Psych.dump(
{ 'reminders' => {
# ↑
'reminder_a' => [nil],
# ↑ ↑
'reminder_b' => [nil]
# ↑ ↑
}
so that the resulting YAML document looks like this:
---
reminders:
reminder_a:
-
reminder_b:
-
There is nothing wrong with the YAML file. However you create the file you create it with the following structure:
yaml = {
'reminders' => [
{'reminder_a'=> [nil]},
{'reminder_b'=> [nil]}
]
}
Notice that the contents of yaml['reminders'] is an array. Where it goes wrong is here:
reminders = yaml['reminders']
reminder_a = reminders['reminder_a'] # <= error
# in the question example:
# yml['reminders']['reminder_a'] = [123,456]
Since reminders is an array you can't access it by passing a string as index. You have 2 options:
In my opinion the best option (if you want to access the reminders by key) is changing the structure to use a hash instead of an array:
yaml = {
'reminders' => {
'reminder_a'=> [nil],
'reminder_b'=> [nil]
}
}
With the above structure you can access your reminder through:
yaml['reminders']['reminder_a']
Somewhat clumsy, find the array element with the correct key:
yaml['reminders'].each do |reminder|
reminder['reminder_a'] = [123,456] if reminder.key? 'reminder_a'
reminder['reminder_b'] = [457,635,123] if reminder.key? 'reminder_b'
end
This question is mostly out of interest to understand the functionality of VBScript better. I recognize that I can simply do some casting to know what to expect from my code, but in my situation I want to understand why casting, or any "workaround", is needed. For simplicity, here's the basic idea of my code:
variable1 = 1
Public Function findSomethingInATextString(par1, par2)
[...searching with a Do Until loop code here...]
Result = 1
If([par2 is found in par1]) Then
Result = 0
End If
Return Result
End Function
variable1 = findSomethingInATextString("Hello World", "Hello")
When I run this I get a Type Mismatch error. I don't understand why that's the case. variable1 is an integer and findSomethingInAString() returns an integer. They appear to be the same data type.
I'm working in a restricted environment where I can't do much debugging (it's painfully slow to code in this program...). So at the moment I'm unable to say what data type this is coming out as - I just know that it's apparently not integer.
After all that, and to make sure my question is clear, I'm intrigued to know what the return type of my function is (if someone happens to know), but my real question is: Why isn't the return type matching with variable1?
Use the minimal script
Return
Output
cscript 36633603.vbs
...36633603.vbs(1, 1) Microsoft VBScript runtime error: Type mismatch: 'return'
to prove to yourself, that just mentioning return in a VBScript will throw a type mismatch error.
Believe JosefZ's comment that VBScript returns function values by assigning to the function's name. Better: Read the docs (before you try to write code).
Evidence:
Function f1()
f1 = 1
End Function
WScript.Echo f1(), TypeName(f1())
Output:
cscript 36633603.vbs
1 Integer
I have date_duration variable and i want to convert it to int, I found the same topic here, about how to convert for output by <<, but i don't want it. I have to use integer value for arithmetic operations. How to convert it to string or integer? I can write it to file and then fscanf but it's idiot method.
You can use the days() method to get the number of days (as a value, not an object).