Ruby: divisible by 4 - ruby

This works fine, but I want to make it prettier - and accommodate all values that are divisible by 4:
if i==4 || i==8 || i==12 || i==16 || i==20 || i==24 || i==28 || i==32
# ...
end
Any clever, short method to do this?

Try this:
if i % 4 == 0
This is called the "modulo operator".

There's also modulo, which allows you to do
420.modulo(4).zero?
There's nothing stopping you doing that with %, but it looks weird:
420.%(4).zero?

This is always a good conversation starter:
if (i & 3).zero?

Related

How to return to beginning of program from inside of if statement?

I'm practicing some basic coding, I'm running a simple math program running in the terminal on Visual Studio Code.
How do I create an option to return to the beginning of the program, or exit the program after getting caught in an if statement?
Example:
#beginning of program
user_input=input('Please select "this" or "that": ')
findings=user_input
If findings == this:
print(this)
# How can I redirect back to first user input question, instead
# of just ending here?
if findings == that:
print (that)
# Again, How do I redirect back to first user input, instead of
# the program ending here?
# Can I setup a Play_again here with options to return to user_input,
# or exit program? And then have all other If statements
# redirect here after completion? How would I do that? with
# another If? or with a for loop?
#end program
You can try wrapping the whole program in a while loop like this:
while(True):
user_input=input('Please select "this" or "that": ')
this = 'foo'
if user_input == this:
print(this)
continue
if user_input == this:
print(this)
continue
Unfortunately, that 'another technique' I thought of using didn't work.
Here's the code (the first example modified):
import sys
def main():
# Lots of setup code here.
def start_over():
return #Do nothing and continue from the next line
condition = 1==1 #Just a sample condition, replace it with "check(condition)".
float_condition = condition
def play(*just_define:bool):
if not just_define:
play_again = input('play again? "y" or "n"')
if play_again == 'y':
start_over() #Jump to the beginning of the prohram.
if play_again == 'n':
sys.exit() #Exit the program
while True:
if float_condition == True:
# print(float_condition)
play() #skip to play_again from here?
if float_condition == False:
#print(float_condition)
play() #skip to play_again from here?
#I removed the extra "main()" which was here because it'd cause an infinite loop-like error.
main()
Output:
play again? "y" or "n"y
play again? "y" or "n"n
Process finished with exit code 0
The * in the play(*just_define:bool) function makes the just_define parameter optional. Use the parameter if you want to only tell Python to search for this function, so it doesn't throw a ReferenceError and not execute anything that's after the line if not just_define:. How to call like so: play(just_define=True).
I've used nested functions. I've defined play so that you can call it from other places in your code.
Thanks to #Hack3r - I was finally able to choose to return back to the beginning of the program or exit out. But it resulted in a new issue. Now my print(results) are printing 4 or 5 times...
Here is the actual code I built and am working with:
def main():
math_Options=['Addition +','Subtraction -','Multiplication *','Division /']
math_func=['+','-','*','/']
for options in math_Options:
print(options)
print('Lets do some Math! What math function would you like to use? ')
while True:
my_Math_Function = input('Please make your choice from list above using the function symbol: ')
my_Number1=input('Please select your first number: ')
x=float(my_Number1)
print('Your 1st # is: ', x)
my_Number2=input('Please select your Second Number: ')
y=float(my_Number2)
print('Your 2nd # is: ', y)
z=float()
print('')
for Math_function in math_func:
if my_Math_Function == math_func[0]:
z=x+y
if my_Math_Function == math_func[1]:
z=x-y
if my_Math_Function == math_func[2]:
z=x*y
if my_Math_Function == math_func[3]:
z=x/y
if (z % 2) == 0 and z>0:
print(z, ' Is an EVEN POSITIVE Number')
if (z % 2) == 1 and z>0:
print(z, ' IS a ODD POSTIVE Number')
if (z % 2) == 0 and z<0:
print(z, ' Is an EVEN NEGATIVE Number')
if (z % 2) ==1 and z<0:
print(z, ' IS a ODD NEGATIVE Number')
if z==0:
print(z, 'Is is Equal to Zero')
print('')
play_again=input('Would you like to play again? "y" or "n" ')
if play_again == 'y':
continue
if play_again == 'n':
break
main()
main()

For-loop in lua with löve2D, deleting variable

i'm a bit beginner about coding, and my english isn't great, i hope i'll be able to make my question clear:
So I have a for-loop in my code, and 2 if in it, in each if, I see if something is true or false, if it's true, I delete a portion of the loop. like that:
for n=#Test,1, -1 do
if Test[n].delete == true then
table.remove(Test, n )
end
if Test[n].y > 0 then
table.remove(Test, n )
end
end
kind of like that, and my problem is, if the first if make Test[n] being deleted, then the game crash at the next if because Test[n] Doesn't exist anymore. I solved the problem by making 2 for-loop, one for each if.
But I saw someone who did it without 2 for-loop, and it's not crashing, I tried to figure what was wrong but I can't find it.
If someone could find what is wrong with what I wrote, I would be thankful!
So here is the moment that makes problem in my code, on line 9, if the condition are met, i table.remove(ListeTirs, n ), then on line 17, when code try to find it again for test it, it bug :
for n=#ListeTirs,1, -1 do
if ListeTirs[n].Type == "Gentils"
then local nAliens
for nAliens=#ListeAliens,1,-1 do
if
Collide(ListeTirs[n], ListeAliens[nAliens]) == true
then
ListeTirs[n].Supprime = true
table.remove(ListeTirs, n )
ListeAliens[nAliens].Supprime = true
table.remove(ListeAliens, nAliens)
end
end
end
if
ListeTirs[n].y < 0 - ListeTirs[n].HauteurMoitie or ListeTirs[n].y > Hauteur + ListeTirs[n].HauteurMoitie or ListeTirs[n].x > Largeur + ListeTirs[n].LargeurMoitie or ListeTirs[n].x < 0 - ListeTirs[n].LargeurMoitie
then
ListeTirs[n].Supprime = true
table.remove(ListeTirs, n)
end
end
I hope it's clear, I could post the whole code but I don't feel it's necessary, if it is, I will add it.
Thank you :)
for n=#Test,1, -1 do
local should_be_removed
-- just mark for deletion
if Test[n].delete = true then
should_be_removed = true
end
-- just mark for deletion
if Test[n].y > 0 then
should_be_removed = true
end
-- actually delete (at the very end of the loop body)
if should_be_removed then
table.remove(Test, n )
end
end

Is this a bug on RubyMonk or something flaw in my logic thinking?

I am learning Ruby with Rubymonk.com
Below is the project description:
Hiring Programmers - Boolean Expressions in Ruby
Let us say you are trying to recruit team-members for your new startup! Given a candidate, you need an expression that will tell you whether they fit into certain types. This is how a candidate object would look:
candidate.years_of_experience = 4
candidate.github_points = 293
candidate.languages_worked_with = ['C', 'Ruby', 'Python', 'Clojure']
candidate.applied_recently? = false
candidate.age = 26
We are looking to hire experienced Ruby programmers. Our ideal candidate has 2 or more years of experience, but some programmers become really good even before that. We'll consider their Github points (a nice indicator of a good programmer), and even if they are not experienced, candidates with 500 Github points or more can apply. And there is one more catch: Ruby being a cool and awesome language, a lot of smart youngsters are very good at it. We love those kids, but for this particular job we'd rather have them study at school than work. Let us filter out candidates who are younger than 15. Also we don't want to consider candidates who applied recently for this opening.
Base on above description, I conclude that items listed below must be true:
candidate.languages_worked_with.include?('Ruby')
candidate.years_of_exprience >= 2 || candidate.github_points >= 500
candidate.age > 15
candidate.applied_recently? == false
And my answer is:
is_an_experienced_programmer = (candidate.years_of_exprience >= 2
|| candidate.github_points >= 500) && candidate.languages_worked_with.include? 'Ruby'
&& (candidate.age > 15) && !(candidate.applied_recently?)
but then answer is:
is_an_experienced_ruby_programmer = (candidate.years_of_experience >= 2
|| candidate.github_points >= 500) && (candidate.languages_worked_with.include? 'Ruby')
&& ! (candidate.age < 15 || candidate.applied_recently?)
The only difference between my answer and the answer is:
(candidate.age > 15) && !(candidate.applied_recently?)
above saying candidate must older than 15 and haven't applied recently.
and the answer:
! (candidate.age < 15 || candidate.applied_recently?)
above code basically saying, candidate can not younger than 15 and haven't applied recently.
Aren't they the same? Or something flawed in my logic?
Its almost same only thing you are missing is >=
(candidate.age >= 15) && !(candidate_applied_recently?)
and that's why you might be getting the wrong answer.
Hope it helps.
I conclude that there is something wrong in the Testing Logic with the project on RubyMonk:
When I use the code below, I passed the test:
is_an_experienced_ruby_programmer = (candidate.years_of_experience >= 2 || candidate.github_points >= 500) && (candidate.languages_worked_with.include? 'Ruby') && !candidate.applied_recently? && (candidate.age > 15)
And when I use below, I failed the test:
is_an_experienced_programmer = (candidate.years_of_exprience >= 2 || candidate.github_points >= 500) && (candidate.languages_worked_with.include? 'Ruby') && (candidate.age > 15) && !(candidate.applied_recently?)
So
!(candidate.applied_recently?) && (candidate.age > 15)
is different to
(candidate.age > 15) && !(candidate.applied_recently?)
in Rubymonk's mind?

Better way to map multiple values (inject)

Please suggest a better (Ruby-ish) way to summarise mutiple entries in one go given the code below:
def summary_totals
pay_paid, pay_unpaid = 0, 0
rec_paid, rec_unpaid = 0, 0
net_paid, net_unpaid = 0, 0
summary_entries.each do |proj_summary|
pay_paid += proj_summary.payable.paid || 0
pay_unpaid += proj_summary.payable.unpaid || 0
rec_paid += proj_summary.receivable.paid || 0
rec_unpaid += proj_summary.receivable.unpaid || 0
net_paid += proj_summary.net.paid || 0
net_unpaid += proj_summary.net.unpaid || 0
end
pay = PaidUnpaidEntry.new(pay_paid, pay_unpaid)
rec = PaidUnpaidEntry.new(rec_paid, rec_unpaid)
net = PaidUnpaidEntry.new(net_paid, net_unpaid)
ProjectPaymentsSummary.new(pay, rec, net)
end
Update: All you need to do is to rewrite the each loop (which sums up 6 variables) in a better Ruby style.
"Better" could be subjective, but I guess you want to use inject to do the summing. The symbol argument to inject can be used to make it nice and concise. If you pass the result directly to your constructors, there's no need for the local variables, eg:
pay = PaidUnpaidEntry.new(
summary_entries.map { |e| e.payable.paid }.inject(:+),
summary_entries.map { |e| e.payable.unpaid }.inject(:+)
)
# etc

Force to end n if in haml

I have an if:
-12.times do |control|
-dia += 1
-if control == 1
%a#hoy{:href=>'/dias/algo'}<
-else
%a{:href=>'/dias/algo'}<
=dia
%span=dias[rand(7)]
The problem is I need =dia and span elements inside the anchor tag in both cases (true/false), and when I quit one identation it fails, because haml will end the if (which is also normal).
Is there any way to force end an if? I have tried it in many ways, but couldn't find the right way if it exist.
Thanks.
-12.times do |control|
-dia += 1
%a{:id => control == 1 ? "hoy" : "", :href=>'/dias/algo'}<
=dia
%span=dias[rand(7)]
Didn't test it but it should work ...

Resources