Explanation needed for this Ruby challenge [closed] - ruby

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need some help understanding this code:
def SimpleAdding(num)
sum = 0
(num + 1).times do |x|
sum = sum + x
end
return sum
end
SimpleAdding(12) #=> 78
SimpleAdding(140) #=> 9870
I am not sure of the method. Why is the method written the way it is? Why is sum on the first line set to 0? And why is sum = sum + x used on the third line?

In Ruby, the def keyword delimits the start of a method, in your case named SimpleAdding. It takes one argument (in the parentheses) named num.
In the method body, the variable sum is given the initial value of 0.
The line containing (num + 1).times do |x| tells Ruby to execute the code between the do and end keywords a set number of times (an iterator), in this case num + 1. Remember, num represents the value received in the form of an argument when the method was called.
On the next line, the variable sum (initialized to 0 at the beginning of the method) is assigned the value of itself plus x.
Next line, our iterator ends.
Finally, we return the value stored inside of the variable sum.
And, the end of our method.
Enjoy learning Ruby!

Related

ruby not equal operator doesn't work but equal does [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm very puzzled with this simple method I have where I'm just trying to puts a character of an array if, when compared with the character of another array, it is different.
This works with the == operator but not with the !=
Maybe it has to do with the each loops but I can't see what the error is. Any ideas?
Thanks
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = []
nw_s.each do |char|
vowels.each do |vowel|
if char != vowel
print char
end
end
end
end
remove_vowels("apple")
Nested each is no ruby way of doing this kind of task. You can write this
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = nw_s.map {|k| k unless vowels.include?(k) }.compact
end
remove_vowels("apple")
One line of code instead seven

Ruby if else statement [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 5 years ago.
Improve this question
I am being asked to:
Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise.
This is the code I have come up with:
def first_longer_than_second(first, second)
if first >= second
return true;
else
return false;
end
end
The calls I am making:
first_longer_than_second('pneumonoultramicroscopicsilicovolcanoconiosis', 'k') #=> false
first_longer_than_second('apple', 'prune') #=> true
For some reason on repl.it I only get the output false
And i get this error message on the platform I am actually meant to be completing this task on:
expected #<TrueClass:20> => true
got #<FalseClass:0> => false
Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`expect(actual).to eq(expected)` if you don't care about
object identity in this example.
exercise_spec.rb:42:in `block (2 levels) in <top (required)>'
Tried a number of things, but annoyingly stuck with something that seems should be simple...
Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise.
Your code:
def first_longer_than_second(first, second)
if first >= second
return true;
else
return false;
end
end
First of all, your code doesn't follow the requirements. They ask to compare the lengths of the two arguments. The if condition should be:
if first.length >= second.length
See the documentation of String#length.
Regarding the syntax of Ruby, the semicolons (;) after the statements are not needed. Like in Javascript, a Ruby statement can be terminated using a semicolon but also a newline. The semicolon is useful to separate two statements on the same line.
Next, the same as in Javascript (and many other languages), you can directly return the result of the comparison (and not put it into an if statement that returns true/false):
def first_longer_than_second(first, second)
return first.length >= second.length
end
One last improvement to make it look like Ruby (and not Javascript or PHP): a Ruby function returns the value of the last expression it computes; this makes the presence of the return keyword superfluous here.
Your code should be:
def first_longer_than_second(first, second)
first.length >= second.length
end

How do i print a string with repeated names followed by a number - Ruby? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How do i print a name Ex. John1 and then print after John2, john3, john4, john5 and so one in an infinite number
I started using ruby today and I'm having some trouble figuring this out. I've searched some but can't find anything so how would I do this?
It's to mass produce accounts to the staff of a certain company and I found ruby to be the smartest to write it in and I will never use it again after this
Keep it simple.
puts (1..5).map { |n| "john#{n}" }
john1
john2
john3
john4
john5
The class Range includes the module Enumerable (as does the classes Array, Hash and others). By doing so, instances of Range (such as 1..5) gain the use of all of Enumerable's instance methods. One of Enumerable's instance methods is used here: Enumerable#map.
For printing a simple series like this:
n = 1
loop do
print 'john%d, ' % n
n += 1
end
That will never terminate, which makes it kind of silly. Maybe what you want is a bounded range:
list = (1..10).map do |n|
'john%d' % n
end.join(', ')
puts list
You can adjust the start and end values as necessary.
Perhaps use an enumerator here:
enum = Enumerator.new do |y|
i = 1
loop do
y << "John#{i}"
i += 1
end
end
enum.next #=> "John1"
enum.next #=> "John2"
enum.next #=> "John3"
Then use any one of the methods available to instances of Enumerator. Here we've used Enumerator#next to get the next "John" string.
One simple way is using a for loop. First declare an empty string variable that will hold our contents.
One important thing to consider is the index of the loop. If it's the last item, we do not want to add a separator like ", "
This is where the conditional comes into play. If the index is less than the last, we will add a comma and space, otherwise just the name.
Interpolation is done by wrapping a variable inside #{ and }
str = ""
for i in 1..5
str += i < 5 ? "john#{i}, " : "john#{i}"
end
Returns
"john1, john2, john3, john4, john5"

Having trouble using the modulo operator with a method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have two methods turn_count(board) and current_player(board). The turn_count(board) method, which returns the number of "X"s and "O"s in an array is working appropriately. But the current_player(board) method, which is supposed to puts "X" if turn_count(board) is even and "O" if turn_count(board) is odd keeps giving me an error. The error is:
/Users/john/Desktop/test file.rb:13:in current_player': undefined method%' for nil:NilClass (NoMethodError)
from /Users/john/Desktop/test file.rb:18:in `'
Clearly it's saying there's an issue with the modulo operator being used, but i'm not sure why and have been wracking my brain trying to figure it out.
Any help is greatly appreciated!
def turn_count(board)
count = 0
board.each do |x| if x == "X" || x == "O"
count = count + 1
end
end
puts count
end
def current_player(board)
if turn_count(board) % == 0
puts "X"
else
puts "O"
end
end
The problem is you are using % on a NilClass. Your turn_count() method returns nil. Check what happens if you replace puts count with count.

Instance vs Class variables and Random Numbers Ruby [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 8 years ago.
Improve this question
Hello I am writing a code for a simple die of (n) sides and it works fine:
class Die
def initialize(sides)
#sides = sides
raise ArgumentError if sides < 1
end
def roll
roll_number = rand(#sides) + 1
end
end
However, when I change my initialized variable from instance to class the random numbers generated go from integers to a bunch of small floating point numbers around 1.
class Die
def initialize(sides)
HERE --> ##sides = sides
raise ArgumentError if sides < 1
end
def roll
roll_number = rand(#sides) + 1
end
end
I wanted to know what may cause this difference?
In the second code snippet, you're initializing the class variable ##sides but still passing the instance variable #sides to rand(). Since #sides is not initialized, you are passing nil to the call to rand(), so Kernel#rand gives a float instead of integer.
There's an error in your code, in your second version of Die you actually never call the right variable in your roll method.
It should be:
def roll
roll_number = rand(##sides) + 1
end
Instead yours was evaluating to:
roll_number = rand(nil) + 1
According to the rand library if you don't supply an argument rand returns a pseudo-random floating point number between 0.0 and 1.0, including 0.0 and excluding 1.0.

Resources