This code from my developer below... does it expect something like "1 - January" and try to parse it into something else?
I changed the code on my form so now the value being passed to this controller is just "1" instead of "1 - January"
How can I fix this so I don't get the "can't convert nil into string" error?
def get_expiry_month_number(monty_det, expiry_year)
if MONTH_NAMES.include? monty_det
month_number = MONTH_NAMES.index(monty_det)
month_number = MONTH_NUMBERS[month_number]
expiry_year = month_number.to_s + expiry_year[expiry_year.length-3..expiry_year.length-1]
return expiry_year
end
end
In your example you are running into the problem that one of your strings in your calculation for year is nil. Most likely this one,
expiry_year[expiry_year.length-3..expiry_year.length-1]
You can try and fix this by calling to_s on the culprit variable, thus converting the nil into '' and then concatenated.
Like so: expiry_year = month_number.to_s + expiry_year[expiry_year.length-3..expiry_year.length-1].to_s
However, this may have other seen consequences and isn't recommended. A better approach would be to find out why something you expect is a string is turning out to be empty, and perhaps displaying an appropriate error.
Could you explain a little bit more about what the function is supposed to do? And perhaps the value of expiry_year and monty_det when the error occurs? puts statements can be a big help here.
I guess that get_expiry_month_number('january', 2011) would return: 1011.
Indeed:
month_number should return 1 for january
expiry_year[expiry_year.length-3..expiry_year.length-1] returns the 3 last characters of 2011 => 011
Related
Did I try google?
Yes, I tried stack overflow, google, rubydocs, bunch of websites but there are minimal results to this and it's only ever mentioned indirectly. So yes, I did a lot of searching.
What's working?
I run the following query:
requests = Request.where("customer_id = ?
AND request_method != ?
AND request_time
BETWEEN ? AND ?",
customer.id, "OPTIONS", start_time, end_time).group('request_time')
As a result I get a bunch of values from the Database which look like this and this is CORRECT:
#<ActiveRecord::Relation[#<Request id: 171792, request_time: "2022-04-04 14:07:20">,
#<Request id: 171787, request_time: "2022-04-04 14:06:02">...]
NOTE: I didn't paste all the values because they have a similar structure.
What's the problem?
After running the query I want to pass it to the variable dates_init_hash = {} and merge it whilst counting into data[:requests]:
dates_init_hash = {}
(start_time.to_date..end_time.to_date).each do |date|
dates_init_hash[date] = 0
end
data[:requests] = dates_init_hash.merge(requests.count)
Unfortunately, I always seem to be getting the error:
ERROR -- : TypeError: no implicit conversion of Fixnum into Hash
Expected
I should be getting a Hash like the following:
{ "2022-03-24"=>2, "2022-03-25"=>1, "2022-03-28"=>3, "2022-03-29"=>11}
What I tried
I tried to convert the results to a hash before passing it over but this gave me the error that the .to_h method doesn't exist
data[:requests] = dates_init_hash.merge({requests: requests.count }) works half-way still causing errors
Questions
Why am I getting a Fixnum and why won't this work? How can I improve this? What would be the right way to solving this? I appreciate any kind of help.
Why is the error happening?
You are getting the error because when you run:
data[:requests] = dates_init_hash.merge(requests.count)
dates_init_hash is a hash, and requests.count is a number. So you are trying to merge a number into a hash, what is not allowed.
How can I fix it?
If what you want is to have the dates_init_hash with a mapping date => number of requests that date, you can do the following:
# initializes dates_init_hash with desired dates
dates_init_hash = {}
(start_time.to_date..end_time.to_date).each do |date|
dates_init_hash[date.iso8601] = 0
end
# iterates over reuests and add 1 to the date in dates_init_hash for each request in the desired date
requests.each do |request|
date = Date.parse(request[:request_time]).iso8601
next if dates_init_hash[date].nil?
dates_init_hash[date] += 1
end
Then, dates_init_hash will be something like
{"2022-04-04"=>1, "2022-04-05"=>0, "2022-04-06"=>1, "2022-04-07"=>0}
function Main(Inhalt)
print(string.len(Inhalt))
end
Main(Bla)
This is just a example, I run in multiple problems like: "input:3: bad argument #1 to 'len' (string expected, got nil)" (Like here), or anything else with unexpected.
I'm kinda new to this, so please explain it to me from ground up I'm trying to figure out for a pretty long time. I already tried to convert this to a string with tostring(), but yes I'm missing something. Thanks for your help.
In this case Bla either needs to be a string which you can fix by putting quotes around it
function Main(Inhalt)
print(string.len(Inhalt))
end
Main("Bla")
or needs to be a variable that contains a string
Bla="test string"
function Main(Inhalt)
print(string.len(Inhalt))
end
Main(Bla)
Not a lua expert but it seems like you're trying to get the length of the string value Bla. The way you've written it right now does not indicate Bla is of string type. If you change it to the following, this should work.
function Main(Inhalt)
print(string.len(Inhalt))
end
Main("Bla")
Try this:
string1 = "Bla"
Main(string1)
In your code snippet Bla is not defined. Strings are surrounded by "".
I am trying to replace some characters in a text block. All of the replacements are working except the one at the beginning of the string variable.
The text block contains:
[FIRST_NAME] [LAST_NAME], This message is to inform you that...
The variables are defined as:
$fname = "John";
$lname = "Doe";
$messagebody = str_replace('[FIRST_NAME]',$fname,$messagebody);
$messagebody = str_replace('[LAST_NAME]',$lname,$messagebody);
The result I get is:
[FIRST_NAME] Doe, This message is to inform you that...
Regardless of which tag I put first or how the syntax is {TAG} $$TAG or [TAG], the first one never gets replaced.
Can anyone tell me why and how to fix this?
Thanks
Until someone can provide me with an explanation for why this is happening, the workaround is to put a string in front and then remove it afterward:
$messagebody = 'START:'.$messagebody;
do what you need to do
$messagebody = substr($messagebody,6);
I believe it must have something to do with the fact that a string starts at position 0 and that maybe the str_replace function starts to look at position 1.
I'm attempting to convert a string date into a date that can be stored in the database. These are my attempts:
params[:event][:start_date] = '03-21-2016'
DateTime.strptime(params[:event][:start_date], '%Y-%m-%dT%H:%M:%S%z')
or
DateTime.strptime(params[:event][:start_date], '%m-%d-%Y')
However I keep getting an invalid date error. I'm not sure what I'm doing wrong.
One way to do it would be this:
date_string = '03-21-2016'
month, day, year = date_string.split('-').map(&:to_i)
DateTime.new(year, month, day)
You need to understand what each fragment (eg %Y) in the format string ('%Y-%m-%dT%H:%M:%S%z') means: read this.
http://apidock.com/rails/ActiveSupport/TimeWithZone/strftime
Once you know this, you can tailor a format string to the date string you have, or expect to get: in this case, "%m-%d-%Y".
When debugging create a new, basic and simple, version of the code and test that.
require 'date'
params = '03-21-2016'
DateTime.strptime(params, '%m-%d-%Y') # => #<DateTime: 2016-03-21T00:00:00+00:00 ((2457469j,0s,0n),+0s,2299161j)>
Note the order for the format: '%m-%d-%Y', which works. That's the problem with your first attempt, where you tried to use%Y-%m-%d. There is NO month21or day2016`.
Your second attempt is valid but your question makes it appear it doesn't work. You need to be more careful with your testing:
params = {event:{start_date:'03-21-2016'}}
DateTime.strptime(params[:event][:start_date], '%m-%d-%Y') # => #<DateTime: 2016-03-21T00:00:00+00:00 ((2457469j,0s,0n),+0s,2299161j)>
I'm developing an app using Grails. I want to get length of array.
I got a wrong value. Here is my code,
def Medias = params.medias
println params.medias // I got [37, 40]
println params.medias.size() // I got 7 but it should be 2
What I did wrong ?
Thanks for help.
What is params.medias (where is it being set)?
If Grials is treating it as a string, then using size() will return the length of the string, rather than an array.
Does:
println params.medias.length
also return 7?
You can check what Grails thinks an object is by using the assert keyword.
If it is indeed a string, you can try the following code to convert it into an array:
def mediasArray = Eval.me(params.medias)
println mediasArray.size()
The downside of this is that Eval presents the possibility of unwanted code execution if the params.medias is provided by an end user, or can be maliciously modified outside of your compiled code.
A good snippet on the "evil (or lack thereof) of eval" is here if you're interested (not mine):
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
I think 7 is result of length of the string : "[37,40]"
Seems your media variable is an array not a collection
Try : params.medias.length
Thanks to everyone. I've found my mistake
First of all, I sent an array from client and my params.medias returned null,so I converted it to string but it is a wrong way.
Finally, I sent and array from client as array and in the grails, I got a params by
params."medias[]"
List medias = params.list('medias')
Documentation: http://grails.github.io/grails-doc/latest/guide/single.html#typeConverters