Creating a variable to measure string length - ruby

So I'm curious as to what I'm missing here. I have a program for school and part of the program requires that I measure the length of the input string. I have it laid out as "if String==6" which you can see in my code below. My professor would rather it be stored in a variable and that I use the .length method to measure it. His exact words are as follows, "To see if the ticket number is greater than six characters, you need to store it in a variable. Then, on line 19, you can check it by using ticket.length == 6."
I tried using his method and I put "ticket_number.length==6." but that returns an error. Im not sure why, isnt "ticket_number" the variable that needs measured? Or do I need to create another variable just for ticket length? I'm sure there is an easy answer, I just cant seem to find it. Thanks in advance for any and all help!
begin
print "Please enter your six-digit ticket number."
ticket_number=gets.chomp.to_i
ones_digit=ticket_number%10
truncated_number=ticket_number/10.floor
remainder=truncated_number%7
if String=6 and ones_digit==remainder and ticket_number>0
print "Your ticket number is valid."
else
print "Your ticket number is invalid."
end
end while ticket_number>0

There's a couple of problems here but the biggest one is that converting to an integer means you've forfeited your opportunity to test vs. length:
ticket_number = gets.chomp
if (ticket_number.length != 6)
puts "Your ticket number must be six digits"
next
end
You can convert after the fact:
ticket_number = ticket_number.to_i
Then do your math.
Ideally you'd wrap this up in a function that, given a ticket number, will return true or false depending on validity. This de-couples it from your display and looping logic, simplifying things.

Related

My flow fails for no reason: Invalid Template Language? This is what I do

Team,
Occasionally my flow fails and its enough test it manually to running again. However, I want to avoid that this error ocurrs again to stay in calm.
The error that appears is this:
Unable to process template language expressions in action 'Periodo' inputs at line '0' and column '0': 'The template language function 'split' expects its first parameter to be of type string. The provided value is of type 'Null'. Please see https://aka.ms/logicexpressions#split for usage details.'.
And it appears in 2 of the 4 variables that I create:
Client and Periodo
The variable Clientlooks this:
The same scenario to "Periodo".
The variables are build in the same way:
His formula:
trim(first(split(first(skip(split(outputs('Compos'),'client = '),1)),'indicator')))
His formula:
trim(first(split(first(skip(split(outputs('Compos'),'period = '),1)),'DATA_REPORT_DELIVERY')))
The same scenario to the 4 variables. 4 of them strings (numbers).
Also I attached email example where I extract the info:
CO NIV ICE REFRESCOS DE SOYA has finished successfully.CO NIV ICE REFRESCOS DE SOYA
User
binary.struggle#mail.com
Parameters
output = 7
country = 170
period = 202204012
DATA_REPORT_DELIVERY = NO
read_persistance = YES
write_persistance = YES
client = 18277
indicator_group = SALES
Could you give some help? I reach some attepmpts succeded but it fails for no apparent reason:
Thank you.
I'm not sure if you're interested but I'd do it a slightly different way. It's a little more verbose but it will work and it makes your expressions a lot simpler.
I've just taken two of your desired outputs and provided a solution for those, one being client and the other being country. You can apply the other two as need be given it's the same pattern.
If I take client for example, this is the concept.
Initialize Data
This is your string that you provided in your question.
Initialize Split Lines
This will split up your string for each new line. The expression for this step is ...
split(variables('Data'), '\n')
However, you can't just enter that expression into the editor, you need to do it and then edit in in code view and change it from \\n to \n.
Filter For 'client'
This will filter the array created from the split line step and find the item that contains the word client.
`contains(item(), 'client')`
On the other parallel branches, you'd change out the word to whatever you're searching for, e.g. country.
This should give us a single item array with a string.
Initialize 'client'
Finally, we want to extract the value on the right hand side of the equals sign. The expression for this is ...
trim(split(body('Filter_For_''client''')[0], '=')[1])
Again, just change out the body name for the other action in each case.
I need to put body('Filter_For_''client''')[0] and specify the first item in an array because the filter step returns an array. We're going to assume the length is always 1.
Result
You can see from all of that, you have the value as need be. Like I said, it's a little more verbose but (I think) easier to follow and troubleshoot if something goes wrong.

how do i use for loop for correct options i gave under print command?

i know how to use for loop and if statement separately but when using together i am stuck on this problem.
print(''' a. mumbai
\n b.delhi
\n c. chennai''')
city=(input('enter your city:'))
for options in city:
print('choose you budget:')
print('''a.2k
\n b. 5k
\n c. 8k''')
else:
print('no hotels found')
i wanted that when i enter one of the options i gave under 'city', it gives me the 'budget' and when i enter something else it prints ' no hotels found' and gives the option to enter the city again until it satisfies one from the given options but instead when i enter anything it shows me the budget and later shows'no hotels found'.
is the for cannot be used for something written inside print or am doing it all wrong?
You need to follow this logic flow for what you want to achieve:
Display City Options
Get the user’s City Options Input
Display the Budget Options
Get the user’s Budget Options Input
Check if there are any offerings in the selected city (matching the value retrieved from Step 2) and budget option value (matching the value retrieved from Step 4)
Display any results from the matches of step 5 or display a message stating that no matches were found.
From my understanding you’re missing Step 4… you’re skipping the retrieval of the user’s budget option input.
You’re missing the if statement (in step 5) hence it’s executing the code found in the else statement.
You need to write the code with searches for the chosen city and budget match… you can use a boolean to retrieve the result of this match… and then write an if statement based on the boolean value to display the hotels which are in the chosen city and offer bookings matching the chosen budget… followed by an else statement displaying the “No hotels found”.
Here’s a fix to your code which was posted in your original post:
print(''' a. mumbai
\n b.delhi
\n c. chennai''')
city=(input('enter your city:'))
for options in city:
print('choose you budget:')
print('''a.2k
\n b. 5k
\n c. 8k''')
budget=(input(‘choose you budget:’)
!! Write code to search matches based
to search for input matches !!
if (boolean match == true)
foreach (resultmatch in resultmatches){
print resultmatch}
else:
print('no hotels found')
You need to write the result matches and if statement code… I included some pseudo code within !! !!

Return the count of courses using satisfies contains XQuery

I have been struggling to return the count of courses from this XML file that contain "Cross-listed" as their description. The problem I encounter is because I am using for, it iterates and gives me "1 1" instead of "2". When I try using let instead I get 13 which means it counts all without condition even when I point return count($c["Cross-listed"]. What am I doing wrong and how can I fix it? Thanks in advance
for $c in doc("courses.xml")//Department/Course
where some $desc in $c/Description
satisfies contains($desc, "Cross-listed")
return count($c)
The problem I encounter is because I am using for
You are quite correct. You don't need to process items individually in order to count them.
You've made things much too difficult. You want
count(doc("courses.xml")//Department/Course[Description[contains(., "Cross-listed"]])
The key thing here is: you want a count, so call the count() function, and give it an argument which selects the set of things you want to include in the count.

Best way to architect unique identifier generation

I have an API in rails that will handle a lot of requests. Lets say millions a day. I want to be able to assign a unique id to each of these requests. The way i am doing it is starting with a uid of 3 letters/numbers and continue up till 9 letters/numbers when the previous bracket is all taken.
One one i am doing it is generate the uid in real time when the request comes, so the app will try to find the first available uid and assign it. But after a while i have the impression that this will impact the performance of the app.
The second way I am thinking is to auto-generate all the possible uids in advance and have a flag assigned to them [free/taken] so that when a request comes in i assign the first free uid to it, which should be very fast if that filed is indexed.
Any suggestions are much appreciated. Thank you
I would just generate a random string and assign it while it doesn't exist. Before I get into that let me just mention that SecureRandom.uuid is the best way to go. It generates random uuids whose chance of collision are mathematically improbable.
Anyway, here is a way to use your own custom random string generator that will only assign if it doesn't already exist:
def generate_random_uid
begin
uid = my_custom_random_string_method
object.uid = uid
end while ObjectModel.exists? uid: uid
object.save
end
The do while block will execute once and set a variable called uid to be a random string you generate in the method my_custom_random_string_method, then in the while part it checks if a record exists whose uid attribute matches the random uid you just generated, if it does it runs the do block again, rinse and repeat until the expression in the while part returns false meaning the uid doesn't exists, then your object is saved and the uid written to the db. This guarantees that you will only ever save the object with a uid that doesn't exist in your db.

Convert to E164 only if possible?

Can I determine if the user entered a phone number that can be safely formatted into E164?
For Germany, this requires that the user started his entry with a local area code. For example, 123456 may be a subscriber number in his city, but it cannot be formatted into E164, because we don't know his local area code. Then I would like to keep the entry as it is. In contrast, the input 089123456 is independent of the area code and could be formatted into E164, because we know he's from Germany and we could convert this into +4989123456.
You can simply convert your number into E164 using libphonenumber
and after conversion checks if both the strings are same or not. If they're same means a number can not be formatted, otherwise the number you'll get from library will be formatted in E164.
Here's how you can convert
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
String formattedNumber = phoneUtil.format(inputNumber, PhoneNumberFormat.E164);
Finally compare formattedNumber with inputNumber
It looks as though you'll need to play with isValidNumber and isPossibleNumber for your case. format is certainly not guaranteed to give you something actually dialable, see the javadocs. This is suggested by the demo as well, where formatting is not displayed when isValidNumber is false.
I also am dealing with this FWIW. In the context of US numbers: The issue is I'd like to parse using isPossibleNumber in order to be as lenient as possible, and store the number in E164. However then we accept, e.g. +15551212. This string itself even passes isPossibleNumber despite clearly (I think) not being dialable anywhere.

Resources