I'm writing a method and for some reason it's throwing an error whenever I run an each block like this:
array.each do |i|
something_on_i
end
But, it's not throwing an error when I do the same thing like this:
array.each {|i| something_on_i}
Why? I thought the two were identical.
Here's the full code:
Working:
def factor(num)
i=2
factors=[1]
while i<=num
if (num % i == 0)
factors << i
end
i+=1
end
return factors
end
def Division(num1,num2)
facs1=factor(num1)
facs2=factor(num2)
common=[]
***facs2.each {|i| common << i if facs1.include?i}***
return common.max
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
Division(STDIN.gets)
Not working:
def factor(num)
i=2
factors=[1]
while i<=num
if (num % i == 0)
factors << i
end
i+=1
end
return factors
end
def Division(num1,num2)
facs1=factor(num1)
facs2=factor(num2)
common=[]
***facs2.each do |i|
if facs1.include?(i)
common << i
end
end***
return common.max
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
Division(STDIN.gets)
The error I get is:
(eval):334: (eval):334: compile error (SyntaxError)
(eval):323: syntax error, unexpected kDO_COND, expecting kEND
facs2.each do |i|
^
(eval):324: syntax error, unexpected tIDENTIFIER, expecting kDO or '{' or '('
(eval):334: syntax error, unexpected kEND, expecting $end
Thanks to the great help in the comments from everyone, it appears this is just an issue with Coderbyte and Repl.it, rather than an issue with the code itself. The code runs just fine in irb. #Darek Nedza pointed out that Coderbyte and Repl.it are only running Ruby 1.8.7, which is likely the problem.
Solution:
For strange errors on Repl.it or Coderbyte, just double check in irb
Related
class LineAnalyzer
##highest_wf_count=[]
##highest_wf_words=[]
attr_accessor :highest_wf_count ,:highest_wf_words ,:content , :line_number
def initialize(line,num)
#content=line
#line_number=num
calculate_word_frequency(#content,#line_number).call
end
def calculate_word_frequency(con,num)
#content,#line_number=con,num
#arr= #content.split()
#arr.map do |txt|
#count=0
#i=0
while #i<#content.length
#count+=1 if txt.eql?(#arr[#i])
#i+=1
end
##highest_wf_count[#line_number]= #count
##highest_wf_words[#line_number]= txt
#arr.delete(txt)
end
end
end
class Solution < LineAnalyzer
attr_accessor :analyzers, :highest_count_across_lines, :highest_count_words_across_lines
def initialize
#analyzer=[]
#highest_count_across_lines=0
#highest_count_words_across_lines=[]
end
def analyze_file()
#arr=IO.readlines(ARGV[0])
#analyzers=Array.new(#arr.length){LineAnalyzer.new}
#i=0
#analyzer.each do |obj|
obj(#arr[#i],#i)
#i+=1
end
end
def calculate_line_with_highest_frequency()
#highest_count_across_lines = ##higest_wf_count.max
#i=0
##highest_wf_count.each do |count|
#highest_count_words_across_lines.push ##highest_wf_words[#i] if count==#highest_count_across_lines
#i+=1
end
end
The above code is to calculate word frequency in a text file
Whenever I try to run this below command I get the following error int the intialize function in LineAnalyzer class
ruby module2_assignment.rb test.txt
Error : `initialize': wrong number of arguments (given 0, expected 2) (ArgumentError)
Since I am a beginner in Ruby I can't figure out the error.
The issue is in this line
#analyzers=Array.new(#arr.length){LineAnalyzer.new}
LineAnalyzer's constructor requires two parameters, you're passing none
well, the issue of initialize: wrong number of arguments can be resolved in passed arguments into LineAnalyzer.new, but we still have broken script after those changes, so, as I see, this script in [WIP] status, and we need to make some more changes to make it works.
If you can share more details about the goal of analyzing here, it would be nice.
so, go to code, we need to remove call from this line:
calculate_word_frequency(#content,#line_number)
and fix initializer logic here:
def initialize
#analyzers=[]
#highest_count_across_lines=0
#highest_count_words_across_lines=[]
end
def analyze_file()
#arr=IO.readlines(ARGV[0])
#i=0
#arr.each do |line|
#analyzers << LineAnalyzer.new(line,#i)
#i+=1
end
end
btw you have a typo in this line:
#highest_count_across_lines = ##higest_wf_count.max
should be:
#highest_count_across_lines = ##highest_wf_count.max
so, we've resolved issue, but it still not good, coz output is nothing:
ruby module2_assignment.rb test.txt
Test text
Test text
Test text
1
1
1
coz should be something like this:
module2_assignment.rb test.txt
1
2
3
"The following words have the highest word frequency per line: "
"[\"test\", \"text\"] (appears in line 1)"
"[\"test\", \"text\"] (appears in line 2)"
"[\"test\", \"text\"] (appears in line 3)"
So, I think we have 2 options here:
invest some more efforts to make it works
try to find a similar solution
we can use this worked solution of module2_assignment, for example:
https://github.com/zbristor/rubyWordFrequency/blob/2417324381378f6be76485f6271465cd641ec0ff/module2_assignment.rb
I hope it's help
I am trying to make sense of why Ruby reported the syntax error that it did , and why it could not be more clear. The following code snippet is giving me a "syntax error, unexpected end"
# #param {NestedInteger[]} nested_list
# #return {Integer}
def depth_sum(nested_list)
queue = Queue.new
nested_list.each { |element| queue.enq element }
result = 0
level = 1
until queue.empty?
size = queue.size
size.times do
element = queue.pop
if element.is_integer
result += level * element.get_Integer
else
element.each { |elem| queue.enq(elem) }
end
end
level++
end
end
I then figured out that Ruby does not have the ++ operator , so i replaced level++ with level+=1 and the code worked. But why was Ruby's syntax error message so cryptic about an unexpected end when in fact my error was not due to the "end" but because I was using a ++ operator which is not used in Ruby.
In Ruby, it is allowed to have whitespace between an operator and its operand(s). This includes newlines, and it includes unary prefix operators. So, the following is perfectly valid Ruby:
+
foo
It is the same as
+ foo
which is the same as
+foo
which is the same as
foo.+#()
The following is also perfectly valid Ruby:
foo++
bar
It is the same as
foo ++ bar
which is the same as
foo + + bar
which is the same as
foo + +bar
which is the same as
foo.+(bar.+#())
So, as you can see, the line
level++
on its own is not syntactically invalid. It is the end on the next line that makes this invalid. Which is exactly what the error message says: you are using the unary prefix + operator, so Ruby is expecting the operand, but instead finds an end it was not expecting.
class Fracpri
attr_accessor:whole, :numer, :denom, :dec, :flofrac
def initialize()
puts "Hey! It's an empty constructor"
end
def getFraction(whole,numer,denom)
#whole=whole
#numer=numer
#denom=denom
end
def showFraction
puts "#{whole} #{numer}/#{denom}"
end
def +=(obj)
if(self.whole+(self.numer.to_f/self.denom.to_f) < obj.whole+(obj.numer.to_f/obj.denom.to_f))
puts "Yes"
else
puts "No"
end
end
end
puts "10 question"
r3=Fracpri.new()
r3.getFraction(1,2,3)
r2=Fracpri.new()
r2.getFraction(4,6,5)
r1=Fracpri.new()
r1.getFraction(2,6,5)
r1 += r2
this is the error message I'm getting:
syntax error, unexpected '=', expecting ';' or '\n'
def +=(obj)
^
syntax error, unexpected keyword_end, expecting end-of-input
suggest me how to rectify this error so that i can perform overloading,i need to add a constant using "+=" operator
It is not possible to override =, nor variants such as +=. These are built in keywords and not methods such as +.
If you change your patch from def +=(obj) to def +(obj), you can still call r1 += r2 and it will have the same effect as if you'd patched +=. This is because += is calling your patched + method under the hood.
By the way, your + method doesn't actually return a value so any time you call += it will always result in nil .... but it seems like this is still a WIP so hopefully you can sort that bit out.
I'm trying to complete an exercism.io test file which compares two strings and adds one to a counter each time there is a difference between the two strings. I've written my class, but for some reason it won't run in terminal. I've compared my code with several examples of syntax online and don't see why it won't run. Any help would be much appreciated.
Here's my class:
class Hamming
def compute(str1, str2)
distance = 0
length = str1.length
for i in 0..length
if str1[i] != str2[i] then
distance++
end
end
return distance
end
end
And here's a relevant bit of test file:
class HammingTest < Minitest::Test
def test_identical_strands
assert_equal 0, Hamming.compute('A', 'A')
end
end
Lastly, here's the error I'm getting:
hamming_test.rb:4:in `require_relative': /Users/Jack/exercism/ruby/hamming/hamming.rb:8: syntax error, unexpected keyword_end (SyntaxError)
/Users/Jack/exercism/ruby/hamming/hamming.rb:12: syntax error, unexpected end-of-input, expecting keyword_end
from hamming_test.rb:4:in `<main>'
You don't need then after condition in if statement.
Use two spaces instead of four for indentation in Ruby.
(Direct cause of your error) there's no ++ operator in Ruby. You should have
distance += 1
I was working with Java for a few months and am transitioning back to Ruby now. I am getting a weird error from the following code:
def count_divisors
divisor_hash = {}
25.times do |i|
divisor_hash[i] = find_dividends(i)
end
puts divisor_hash
end
def find_dividends(i)
count = 0
1000.times do |k|
if i % ( k + 1 ) == 0
count++
end
end
count
end
count_divisors()
This code is generating the following error:
test.rb:14: syntax error, unexpected keyword_end
test.rb:19: syntax error, unexpected end-of-input, expecting keyword_end
This error does not occur when I remove the if statement. I am not sure why. I know every if statement needs an end statement, for some reason it seems upset by the placement of that end statement though.
Change the count++ to count += 1 Ruby does not support incremental operator.