Division with if condition [closed] - ruby

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I just start learning ruby with an online course and in my very first exercise, I can't complete the challenge. I have to create functions to sum, subtract, multiply and divide that meet the specs conditions.
For the division, I need to check if it will divide per 0 or not, give the result or a warning. My code is
def divisao(primeiro_numero, segundo_numero)
if segundo_numero > 0
primeiro_numero / segundo_numero
else
puts 'Opa! Zero como divisor'
end
But when I run the specs, I get the following warning
0 examples, 0 failures, 1 error occurred outside of examples
I have changed all the functions, but this one doesn't seem to work.
I added the complete functions and specs file here:https://gist.github.com/isafloriano/86c170400b2f5fc63dc5e8edd8913525
Can anyone give me a clue why this doesn't work?

You are just missing the end of the if-else block:
def divisao(primeiro_numero, segundo_numero)
if segundo_numero > 0
primeiro_numero / segundo_numero
else
puts 'Opa! Zero como divisor'
end # <= this one was missing
end
Some suggestion:
Use English method and variable names. That makes it easier for others to understand your code and to help you.
Try to follow common Ruby conventions right from the start. Ruby code is indented with two spaces.

Here's a compact way to write your four methods.
def add(n1, n2)
f(n1, n2, :+)
end
def subtract(n1, n2)
f(n1, n2, :-)
end
def multiply(n1, n2)
f(n1, n2, :*)
end
def divide(n1, n2)
if n2.zero?
puts "Zero-divide error"
return nil
end
f(n1, n2, :/)
end
def f(n1, n2, op)
n1.public_send(op, n2)
end
add(3, 7) #=> 10
add(5, 7.2) #=> 12.2
subtract(4, 8) #=> -4
subtract(6.1, 3) #=> 3.0999999999999996
multiply(2, 6) #=> 12
multiply(1.0, 6) #=> 6.0
divide(4, 0) #=> nil
Zero-divide error
divide(4, 0.0) #=> nil
Zero-divide error
divide(4, 2) #=> 2
divide(5, 2) #=> 2
divide(5, 2.0) #=> 2.5
See Object#public_send.

Related

Undefined method for 'n' in ruby while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to write an algorithm to solve the math problem Σ n = 1 to 49 of n(n+1). I keep getting an error "undefined method 'n' for main object"
def solver(n)
sum = 0
while n < 49
temp = n(n+1)
n+=1
sum = sum + temp
end
return sum
end
puts solver(1)
Instead of:
temp = n(n+1)
put:
temp = n*(n+1)
The reason you're getting undefined method 'n' for main object is because your code thinks that n(n+1) is calling n() method on the main object. In ruby main refers to the top level object which is an instance of Object
In any case, the solution to your issue is actually multiplying n * (n + 1) rather than calling a method n with argument n + 1
This is because of missing *. Try this solution:
def solver(n)
sum = 0
while n < 49
temp = n*(n+1)
n+=1
sum = sum + temp
end
return sum
end
puts solver(1)

Idiomatic ruby code - simple for each casuing confusing for me [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Im very new to ruby and cant determin if i am using the ruby language correctly. I want find out if any one of an array of numbers is divisible by another number. If so return that number otherwise, return 0.
def is_divisible(nums, n)
nums.each do |m|
if n % m == 0
return n
end
end
0
end
The function works correctly but there are a few aspects to it which i think are not idiomatic of ruby:
Should i check if nums is of a type that can be looped first or catch an exception (coming from php and python I know these think differently but cant tell with ruby yet)
Is there a more concise way to structure the loop and the 2 separate return values
Anything else that isnt correct with this code?
Here are my thoughts:
Naming: Predicate methods in Ruby are named predicate? and not is_predicate, so the name of your method should be divisible? … except that it isn't actually a predicate. It doesn't test whether a number is divisible by another number, rather it finds the first number in an Enumerable which is divisible by another number. That sentence almost sounds like a descriptive method name, doesn't it?
def find_first_divisible(nums, n)
nums.each do |m|
if n % m == 0
return n
end
end
0
end
Naming cont'd: We don't charge you for your characters. You can use more of them if you want ;-) nums is probably okay, n is on the fence, but what the heck is m? In fact, you have a bug there, which is caused precisely by you confusing n and m.
def find_first_divisible(numbers, divisor)
numbers.each do |n|
if n % divisor == 0
return n
end
end
0
end
Guard clauses: For cases like this, where you want to use return (or next) to break out early, I prefer to use a guard clause style of the form "do this if that":
def find_first_divisible(numbers, divisor)
numbers.each do |n|
return n if n % divisor == 0
end
0
end
One line blocks: In this case, the contents of the block are short enough to fit on one line, so I would do that. Note that there are two competing styles for block formatting: one says to always use do/end for multiline blocks and always use {/} for single line blocks. The other says to always use do/end for blocks which are used primarily for their side-effects ("imperative blocks") and {/} for blocks which are used primarily for their return value ("functional blocks"). I prefer the latter style.
def find_first_divisible(numbers, divisor)
numbers.each do |n| return n if n % divisor == 0 end
0
end
Descriptive methods:
def find_first_divisible(numbers, divisor)
numbers.each do |n| return n if (n % divisor).zero? end
0
end
Know the core and standard libraries: This is very important, you don't want to reinvent the wheel!
def find_first_divisible(numbers, divisor)
numbers.find {|n| (n % divisor).zero? } || 0
end
Note how I changed the block style: now we are interested in the return value, there are no side-effects.
Extract methods with meaningful names:
class Integer
def divisible_by?(n) (self % n).zero? end
end
def find_first_divisible(numbers, divisor)
numbers.find {|n| n.divisible_by?(divisor) } || 0
end
Now, the method reads exactly like your description in the question: "within numbers, find the first n which is divisible_by the divisor, and if there is none, the result is 0".
Respect conventions: Last but not least, you should respect the conventions of the community. Methods that search for something should return nil to indicate the absence of a result:
def find_first_divisible(numbers, divisor)
numbers.find {|n| n.divisible_by?(divisor) }
end
Firstly, you should post questions like that to CodeReview SE page. Now to your questions:
It is typical for ruby not to do this to allow duck typing. Rubbyist assumes that programmers are intelligent enough not to call is_divisible method on strings.
Ruby comes with extended Enumerable module which I strongly reccommend to get familiar with: ruby-doc.org/core-2.0.0/Enumerable.html. There is for example method find which will do exactly what you need:
def is_divisible(num, n)
num.find{|number| number % n == 0} || 0
end
Your code seems all right, however I would reconsider its name - i would expect it to return true or false rather than first divisible number. Also when you use simple conditionals to execute just one line use it like:
return n if n % m == 0
You can use similar rules to do end and {} blocks:
nums.each {|m| return n if n % m == 0 }
0
Ruby core Array class contains many useful features, that query and/or re-structure arrays in generic ways when given a block that defines what you are interested in.
Taking your written description:
I want find out if any one of an array of numbers is divisible by another number.
If so return that number otherwise, return 0.
You could do this:
def is_divisible( nums, n )
nums.find { |x| x % n == 0 } || 0
end
using the built-in Array#find method.
However, it would not usually be idiomatic Ruby to return a 0 when you don't have a match. How would you differentiate between a list which contains 0 and the default? So usually I would structure the code like this:
def find_first_divisible( nums, n )
nums.find { |x| x % n == 0 }
end
# If you really need default 0 for no match:
result = find_first_divisible( my_nums, divisor ) || 0
Also the method has become so trivial, and understanding .find statements is easy (compared to looking up definition of a custom method), that I probably would not create a method here unless it was being called in multiple places. That's a personal choice.
For checking types, I tend to do that defensively in factory methods and/or initialize, and not so much elsewhere. That's a more complex discussion though - whole books could be written on typing systems, approaches to validation and testing, and how different languages lend themselves to different approaches.

Why doesn't this algorithm yield the fibonacci sequence under 100? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
a = 1; b = 2
fibonacci = []
while fibonacci.length < 100
fibonacci.push(a)
fibonacci.push(b)
a = a + b; b = a + b
end
push fibonacci
The error message is "undefined method `push' for main:Obj"
You're trying to #push the array itself on the last line! :)
That's what it's complaining about. The push method is being invoked on the 'main' object, and push is not a Kernel method.
I'm guessing you mean puts. Otherwise it looks okay, if somewhat non-idiomatic. Naturally you can find lots of Ruby solutions for this problem on the site that might read a bit more clearly (see here for a recursive one.)
As others have said before the last line should be 'puts'
Also your numbers are wrong.
a = 1; b = 1
fibonacci = []
while fibonacci.length < 100
fibonacci << a
fibonacci << b
a += b
b += a
end
puts fibonacci
But also the fib starts at 1 and the the second element is also 1.
This make you sequence off, if you start at 1, 2
Fib = 1, 1, 2, 3, 5, 8, ...

Ruby puts not putting [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am answering the following question:
Q3: Write a method, is_prime?, that takes a number num and returns
true if it is prime and false otherwise.
You may wish to use the modulo operation: 5 % 2 returns the remainder
when dividing 5 by 2: 1. If num is divisible by i, then num % i == 0.
(You would not be expected to already know about modulo for the
challenge)
but I get no answer back. My final "puts" doesn't seem to be working. Here is my code:
# Q3 method is_prime?
def is_prime? (num)
i = 2
while i <= num
is_divisble = ((num%i) == 0)
if is_divisble
return false
end
i+=1
end
# is not divisible
return true
end
puts 'select a number greater than one and see if it\'s prime'
num = gets.chomp.to_i
puts is_prime?(num)
The code prints fine. However, it always prints true. Remedy: change while i <= num
to while i < num .
i <= num
It is your mistake :).
Your code will increment i until i == num so num%i will always be true at the end.
Just replace it with
i < num

Issue regarding variable alteration in Ruby [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following code...
#organisims.each do |organisim|
randomvalue = rand(10)
prediction = organisim.predict
if prediction == randomvalue
organisim.resources += 1
end
if prediction != randomvalue
organisim.resources -= 1
end
end
I am trying to alter the 'organisims' resources if the prediction it makes matches the randomly generated number. It seems to work fine, -1 if no match, +1 if there is a match.
The problem is that when I iterate this array (of organisims), processing their resources, I recieve duplicates in my output, such as
Cycle 100
Average resouces: 1500
Cycle 101
Average resouces: 1500
Then again,
Cycle 102
Average resouces: 1400
Cycle 103
Average resouces: 1400
Is this an issue with my code (I see no issues with it) or with the psudorandom number generator that Ruby uses?
Cheers as always
Martin
I think this may be an issue of the scope of your accumulator consider this example.
# example Organism class
class Organisim
attr_accessor :predict, :resources, :prediction
def initialize
#resources = 0
end
def predict
#prediction = rand(10)
#prediction
end
end
# initialize #organisims
#organisims = []
100.times do
#organisims << Organisim.new
end
puts "!!!! Starting Organisim Specific Run"
# iterate over array tracking organisim's resource
#organisims.each_with_index do |org, i|
# parrallel assignment
r, p = rand(10), org.predict
#ruby ternery operator
(p == r) ? org.resources += 1 : org.resources -= 1
puts "Run #{i} Prediction: #{org.prediction} Instance Resources: #{org.resources} Overall Resources: n/a"
end
puts "!!!! Cumulative Resource Run"
# resources scoped outside the iteration loop as accumulator
overall_resources = 0
# re-initialize #organisims
#organisims = []
100.times do
#organisims << Organisim.new
end
#organisims.each_with_index do |org, i|
# parrallel assignment
r, p = rand(10), org.predict
#ruby ternery operator
#track class level resource
(p == r) ? org.resources += 1 : org.resources -= 1
#iterate accumulator
(p == r) ? overall_resources += 1 : overall_resources -= 1
puts "Run #{i} Prediction: #{org.prediction} Instance Resources: #{org.resources} Overall Resources: #{overall_resources}"
end
The first iteration loop is like (I think) the one that you have in your question but you're changing the resource within the organisim object instance.
The second iteration your accumulator is outside the scope of your iteration so it grows and shrinks as the objects are acted upon. :-)

Resources