Ruby koans - error with obj.object_id.class - ruby

I'm going through Ruby Koans, and I"m getting hung up on the test_every_object_has_an_id method in about_objects.rb. The supplied code reads like so:
def test_every_object_has_an_id
obj = Object.new
assert_equal __, obj.object_id.class
end
I know that the answer is Fixnum, but, whenever I run path_to_enlightenment.rb, I get the following error message:
custom_require.rb:36:in `require':about_objects.rb:50: syntax error, unexpected $end, expecting keyword_end (SyntaxError) from rubygems/custom_require.rb:36:in `require'
from path_to_enlightenment.rb:7:in `<main>'
Is there some sort of bug in the code as supplied, or am I doing something wrong?

Missing end Keyword
Somewhere else in your files you have a missing end keyword. Some file is reaching the end of the source file before finding the expected keyword. The error clearly tells you so:
custom_require.rb:36:in `require':about_objects.rb:50: syntax error, unexpected $end, expecting keyword_end (SyntaxError) from rubygems/custom_require.rb:36:in `require' from path_to_enlightenment.rb:7:in `<main>'
Check lines 7, 36, and 50 of the named files. That's the problem you need to fix, and has nothing to do with the fact that:
Object.new.object_id.class
#=> Fixnum

It doesn't ask you which class it is, it ask what Fixnum class is. So the answer must be Object
>> Object.new.object_id.class.is_a? Fixnum
#=> false
>> Object.new.object_id.class.is_a? Object
#=> true

Related

Unexpected tIDENTIFIER in function declaration with optional argument

I am trying to declare a class with a few basic functions in it. The function that seems to be causing a problem has an optional argument that passes a symbol in.
class Bag < RandomizerCollection
def initialize()
end
def select(description:Hash, amt=:all)
end
def empty()
end
end
And the error I am getting is:
Traceback (most recent call last):
1: from test.rb:5:in `<main>'
test.rb:5:in `require_relative': /home/osboxes/Documents/Year4/Design/A1/Bag.rb:9: syntax error, unexpected tIDENTIFIER (SyntaxError)
...ef select(description:hash, amt = :all)
... ^~~
/home/osboxes/Documents/Year4/Design/A1/Bag.rb:9: syntax error, unexpected ')', expecting keyword_end
...t(description:hash, amt = :all)
I'm sure this must be something basic but I just can't figure it out. I am new to Ruby and I found similar questions but none helped me find the issue. Any help is appreciated!
You can't define optional arguments (arg=value) after the definition of the keyword arguments (arg: value).
You can correct it in two ways:
Move optional arg before the keywor arg:
def select(amt=:all, description:Hash)
end
Make the second argument a keyword arg:
def select(description:Hash, amt: :all)
end
Worth reading: https://medium.com/podiihq/ruby-parameters-c178fdcd1f4e

Ruby Unidentified Method for nil No Method Error

I'm attempting to run this code:
def get_linedict(filename,source)
`dwarfdump -l #{source} > dwarfline.txt`
linefile = File.new("dwarfline.txt","r")
match = false
linefile.readlines.each do |line|
puts line
if /uri:/ =~ line
file = line.match(/.*\/(.*)"/)[1]
if file == filename
match = true
end
puts file
puts match
end
end
And when I do I get the following error:
assn4.rb:12:in `block in get_linedict': undefined method `[]' for nil:NilClass (NoMethodError)
from assn4.rb:9:in `each'
from assn4.rb:9:in `get_linedict'
from assn4.rb:126:in `block in <main>'
from assn4.rb:80:in `each'
from assn4.rb:80:in `<main>'
If I change my each loop to only print the lines it's reading, it works fine. As I understand it, the error I'm getting comes from something being nil which shouldn't be, but if that error is coming from the each loop, why am I able to print out the file?
I guess you first have to ask if line.match gets something, before calling an element of the desired array.
line.match(/.*\/(.*)"/)[1]
When you call line.match(/.*\/(.*)"/) the result is nil. Then you attempt to access nil as an Array. That is when you get undefined method []' for nil:NilClass.
And as for this part of your question
but if that error is coming from the each loop, why am I able to print out the file?
The each loop is causing your code to fail and halt when the error occurs. Since you are attempting to print file after the errors, you are actually not printing out file on that iteration of the loop.
Be aware that line might not be nil. Your regular expression is probably just not covering all the cases you think it is, so one of the match calls is failing and returning nil.

Error handling for Ruby Kernel method not working

I have found myself in need to execute a string. Current method is to use the Kernel#eval() method. Everything is working fine, but my error handling isn't working. For example, a missing closing quotation mark will completely kill and exit the program.
Here's an excerpt. Any idea why I can't catch the error?
def process(str)
print "\n"
eval(str)
rescue => e
puts e
end
>> process('"')
console.rb:90:in `eval': (eval):1: unterminated string meets end of file (SyntaxError)
from console.rb:90:in `process'
from console.rb:81:in `bouncer'
from console.rb:14:in `block in prompt'
from console.rb:11:in `loop'
from console.rb:11:in `prompt'
from console.rb:97:in `<main>'
According to the documentation:
A rescue clause without an explicit Exception class will rescue all StandardErrors (and only those).
SyntaxError is not a StandardError. To catch it, you have to be explicit, e.g.:
def process(str)
print "\n"
eval(str)
rescue Exception => e
puts e
end
process('"')
Output:
(eval):1: unterminated string meets end of file

Is there any issues to have `end` as a method name?

I am working on a RoR project, and I want to know if I can use end as a method name. It seems to work fine, but I would like to know if this method will bring any issues in the future. I tried and it works:
class Dany
def end
puts 'Hola'
end
end
and this is the output:
Dany.new.end # => Hola
Ruby let's you do this, but you're going to run into all sorts of issues.
# end.rb
class Dany
def end
puts "Hola"
end
def other
end # should puts Hola
end
end
Instead, you will get
end.rb:10: syntax error, unexpected keyword_end, expecting end-of-input
Bottom line: don't do this. Don't use any keywords as a method name.
It is not a good idea to use a keyword as a method name, but as long as you disambiguate the token as a method call, you can use it. It is not practical though.
Dany.new.instance_eval{self.end} # => Hola
Dany.new.send(:end) # => Hola
Dany.new.method(:end).call # => Hola
Dany.new.instance_eval{end} # => syntax error, unexpected keyword_end
The usual disambiguation using () does not seem to work for this case, making it complicated.
Dany.new.instance_eval{end()} # => syntax error, unexpected keyword_end

Why is kernel_required.rb in my stack trace?

I forgot to put the word end, at the end of a if statement,
and got the following error:
/home/***/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require': **/home/****/Desktop/ruby/food_finder/lib/restaurant.rb:84: syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)**
from /home/****/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require'
from /home/****/Desktop/ruby/food_finder/lib/guide.rb:1:in `<top (required)>'
from /home/****/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require'
from /home/****/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require'
from init.rb:14:in `<main>'
my code without errors:
def self.saved_restaurants
# read the restaurant file
restaurants = []
if file_usable?
file = File.new(##filepath, 'r')
file.each_line do |line|
restaurants << Restaurant.new.import_line(line.chomp)
end
file.close
**end** -- > forgotten end
# return instances of restaurant
return restaurants
end
my code with errors:
def self.saved_restaurants
# read the restaurant file
restaurants = []
if file_usable?
file = File.new(##filepath, 'r')
file.each_line do |line|
restaurants << Restaurant.new.import_line(line.chomp)
end
file.close
-- > forgotten end
# return instances of restaurant
return restaurants
end
My questions are:
Why do i get errors that has noting to do with my code?
like the following:
/home/***/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require':
What does this error mean?
When i use the correct syntax for the saved_restaurants method, i don't get any error.
Your file restaurant.rb is read by a method call require in guide.rb, which is defined in kernel_require.rb. Within its method definition, it has this part:
def require path
...
rescue LoadError => load_error
...
raise load_error
end
When you have a syntax error in the file that is read, that will raise a LoadError, which is rescued, and will be raised as an error of require.
If i understand correctly there is a file named guide.rb which does:
require restaurant
Basically, require is a function implemented in kernel_require.rb whose prototype is like:
require path
Here path is restaurant.rb and this function fails because the require function is unable to load the rb file because of syntax error.
Remember you are looking at the call stack so the function with missing end should not show up because that function is not called but only the ruby file is loaded.

Resources