Substitute a string for multiple of 3 - ruby

I'm printing the integers 1-100. However I want to substitute the integers that are multiples of 3 with the string "fizz".
My current code is
if num % 3 == 0
num.sub(/num/, "fizz");
end
It raises "undefined method 'sub'". It is the same when I try gsub. Am I missing something?

sub is for strings, not integers.
Try this :
if num % 3 == 0
"#{num}".sub(/#{num}/, "fizz");
end

You should be able to just puts "fizz". So:
if num % 3 == 0
puts "fizz"
end
Or a more complete example:
(1..100).each do |num|
if num % 3 == 0
puts "Fizz"
end
end
sub & gsub are for strings only and don't work with integers, hence your error.

Related

Is it better way to do that?

I wrote a simple script to sum all digits of positive integer input until 1 digit is left ( for example for input 12345 result is 6 because 1+2+3+4+5 = 15 and 1+5 = 6). It works but is it better way to do that? ( more correct?)
here is a code:
def sum(n)
string=n.to_s
while string.length > 1 do
result=string.chars.inject { |sum,n| sum = sum.to_i + n.to_i}
string=result.to_s
end
puts "Sum of digits is " + string
end
begin
p "please enter a positive integer number:"
number = Integer(gets.chomp)
while number<0
p "Number must be positive!Enter again:"
number = Integer(gets.chomp)
end
rescue
p "You didnt enter integer!:"
retry
end
sum(number)
According to Wikipedia, the formula is:
dr(n) = 1 + ((n − 1) mod 9)
So it boils down to:
def sum(n)
1 + (n - 1) % 9
end
To account for 0, you can add return 0 if n.zero?
You could use divmod (quotient and modulus) to calculate the digit sum without converting to / from string. Something like this should work:
def sum(number)
result = 0
while number > 0 do
number, digit = number.divmod(10)
result += digit
if number == 0 && result >= 10
number = result
result = 0
end
end
result
end
sum(12345) #=> 6
The line
number, digit = number.divmod(10)
basically strips off the last digit:
12345.divmod(10) #=> [1234, 5]
1234 becomes the new number and 5 is being added to result. If number eventually becomes zero and result is equal or greater than 10 (i.e. more than one digit), result becomes the new number (e.g. 15) and the loops starts over. If result is below 10 (i.e. one digit), the loop exits and result is returned.
Short recursive version:
def sum_of_digits(digits)
sum = digits.chars.map(&:to_i).reduce(&:+).to_s
sum.size > 1 ? sum_of_digits(sum) : sum
end
p sum_of_digits('12345') #=> "6"
Single call version:
def sum_of_digits(digits)
digits = digits.chars.map(&:to_i).reduce(&:+).to_s until digits.size == 1
return digits
end
It's looking good to me. You might do things a little more conscise like use map to turn every char into an integer.
def sum(n)
string=n.to_s
while string.length > 1 do
result = string.chars.map(&:to_i).inject(&:+)
string = result.to_s
end
puts "Sum of digits is " + string
end
You could also use .digits, so you don't have to convert the input into a string.
def digital_root(n)
while n.digits.count > 1
array = n.digits
n = array.sum
end
return n
end

Why Can't This Code Find Powers? (Ruby)

App Academy's practice test says their chosen way of finding if an input is a power of 2 is to keep dividing it by 2 on a loop and check whether the end result is 1 or 0 (after having tested for the numbers 1 and 0 as inputs), which makes sense, but why won't this way work?
def try
gets(num)
counter = 0
go = 2 ** counter
if num % go == 0
return true
else
counter = counter + 1
end
return false
end
I can't figure out why this won't work, unless the counter isn't working.
There are a number of problems with your code.
First of all, there is no loop and your counter will reset to zero each time if you intend to use the method in a loop, because of counter = 0.
counter = 0; go = 2 ** counter basically means go = 2 ** 0 which is 1. Therefore num % 1 will always be 0
You actually need to divide the number and change it in the process. 12 % 4 will return 0 but you don't know by that if 12 is a power of 2.
IO#gets returns a string and takes a separator as an argument, so you need to use num = gets.to_i to actually get a number in the variable num. You are giving num to gets as an argument, this does not do what you want.
Try:
# Check if num is a power of 2
#
# #param num [Integer] number to check
# #return [Boolean] true if power of 2, false otherwise
def power_of_2(num)
while num > 1 # runs as long as num is larger than 1
return false if (num % 2) == 1 # if number is odd it's not a power of 2
num /= 2 # divides num by 2 on each run
end
true # if num reached 1 without returning false, it's a power of 2
end
I add some checks for your code. Note, that gets(num) returns a String. Your code is fine, but not for Ruby. Ruby hates type-cross-transform like Perl does.
def try(num = 0)
# here we assure that num is number
unless (num.is_a?(Integer))
puts "oh!"
return false
end
counter = 0
go = 2 ** counter
if num % go == 0
return true
else
counter = counter + 1
end
return false
end
The general problem is "how string could use '%' operator with number?"
Try some code in the interpretator (irb):
"5" % 2
or
"5" % 0

Problems with Modulo operator Ruby: Why am I getting "undefined method `%' for 1..100:Range"?

For some reason I'm getting the error undefined method '%' for 1..100:Range when I run the following code:
[1..100].each do |x|
if x % 3 == 0 && x % 5 == 0
puts "CracklePop"
elsif x % 3 == 0
puts "Crackle"
elsif x % 5 == 0
puts "Pop"
else
puts x
end
end
Any idea what's going on? Any help is much appreciated.
That's the wrong syntax for ranges.
You've made an array with 1 element, and that element is itself the range 1..100. What you've written is equivalent to [(1.100)]. You're iterating over the outer array one time, and setting x to (1..100)
You want (1..100).each, which invokes each on the range, not on an array containing the range.
By doing [1..100] you are not looping from 1 to 100 but on 1..100, which is a Range object, what you really want to do is:-
(1..100).step do |x|
if x % 3 == 0 && x % 5 == 0
puts "CracklePop"
elsif x % 3 == 0
puts "Crackle"
elsif x % 5 == 0
puts "Pop"
else
puts x
end
end
Basically, Range represents an interval, you can iterate over Range as explained here, create an array from Range as explained here and more details on range can be found here.
Just as it says. 1..100 does not have a method %. The expression (1..100) % 3 is undefined.

Ruby file reading

I have a problem reading a file in ruby.
I am trying to read each line of a file, split it based on characters, and store that into an array. That array, which corresponds to each line, has information. I want to check if that array includes the characters "u" "d" "l" or "r" as you can see below.
IF that line doesn't include ANY of those characters, I increase a count variable by one.
The count -= 1 just takes into account a base case.
My problem is that this gives me a wrong count. For example with a text file that reads:
4 0 0 3 3
0 0 d 0.391538986557049
0 1 ur 63.1258159853081 3.14882640637611
0 2 rd 0.0148854629087619 0.019301544005463
0 3 u 15.6415340291405
count is supposed to be 0.
def compute_closed(file)
count = 0
while line = file.gets do
array = line.split(//)
answer = array.include?("u" || "d" || "l" || "r")
if answer != true
count += 1
end
end
count -= 1
puts count
end
Maybe you have a reason for splitting the line up into bits, but if you're just checking for those characters somewhere in the line, why not use a regex?
def compute_closed(file)
count = 0
while line = file.gets do
count += 1 if line =~ /[udlr]/
end
count -= 1
puts count
end
If you absolutely need to split the lines up by character, then you may want to use sets instead of arrays:
def compute_closed(file)
count = 0
while line = file.gets do
cmp_set = Set.new ['u', 'd', 'l', 'r']
input_set = Set.new(line.split(//))
if input_set.intersection(cmp_set).size == 0
count += 1
end
end
count -= 1
puts count
end
Edit: after posting I see my answer is essentially the same as #Philip's, but I'll leave it up for the slightly different treatment.
There are many ways to do this. Here's another:
File.read('f1').each_line.reduce(0) {|t,s| t + (s =~ /[udlr]/ ? 0 : 1)} - 1
Let's try it:
text =<<_
Now is the time
for all good
Rubiests to
spend some
time in Hawaii.
_
File.write('f1', text)
File.read('f1').each_line.reduce(0) {|t,s| t+(s =~ /[udlr]/ ? 0 : 1)} - 1 #=> 1
It returns 2 - 1 => 1 because if finds a 'u,' 'd', 'l' or 'r' in all but the the first and last rows.
Initially, I had
File.read(fname).each_line.each_with_object(0) {|s,t|
t += 1 unless s =~ /[udlr]/ } - 1
but t would not increment. I was puzzled, so emailed my friend #ArupRakshit, who I can always count on to know the answer, or dig until he finds it. It turns out that in
...each_with_object(memo) {|s,memo|
memo must be a mutable object, an important difference between that method and reduce/inject (which is not made clear in the Ruby docs for Enumerable#each_with_object). Thanks, Arup.

How do I iterate in Ruby?

What's wrong with this Ruby code? I'm trying to solve the first Project Euler question.
I think the problem is in the syntax of sum += num, but I can't figure out what the proper syntax for this would be.
sum = 0
num = 0
num2 = 0
loop do
num += 1
if num % 3 == 0
sum += num
break if num > 1000
end
end
loop do
num2 += 1
if num2 % 5 == 0
sum += num2
break if num2 > 1000
end
end
puts sum
Here's an alternative:
(1...1000).select { |x| x % 3 == 0 || x % 5 == 0 }.reduce(:+)
You are making this way more complicated than it needs to be. Also, if the number is a multiple of 3 and 5, it gets added twice. Try something like this:
sum = 0 # initialize the sum
(1...1000).each { |x| # loop from 1 to 1000
sum += x if x % 3 == 0 || x % 5 == 0 # add the number to the sum if it is
# divisible by 3 or 5
}
puts sum # output the sum
This runs, your syntax is okay, but does not give the right answer because, as mentioned, you add multiples of both 3 and 5 twice, once in the first loop, with num, and the second loop, with num2.
So you have two loops, but you actually only need one.
You only need to consider each number once, you can check it to see if it is a multiple of either 3 or 5. This will solve your double-counting issue and also make your code more concise.
Also, like Doorknob shows, the each syntax would save you some lines on those loops. You could also use the for syntax:
for num in (1..1000)
<stuff here>
end
Check out the kinds of loops in "Loops: How to do thousands of operations with a few lines of code.".

Resources