The ruby code
class Word < Array
def g
puts "JJ"
end
end
w = Word.new([4, 6])
puts Word.method(:g)
produces the following error:
main.rb:9:in `method': undefined method `g' for class `#<Class:Word>' (NameError)
from main.rb:9:in `<main>'
because g is an instance method for Word, not its class method.
It looks like it is the method method that in fact threw this error message. I wouldn't be able to explain how such an error message could be produced if that were not the case.
Is it in fact the method method that threw this error message?
Here, we are passing the symbol :g to the method Word.method, and waiting for its execution. The ruby interpreter cannot know beforehand that it's gonna be an error, only when the method method checks for the existence of a function with a name similar to the symbol :g can it (the method) decide that an error exists. The console/interpreter cannot know about the error beforehand.
Yes. The description:
in `method'
in the error message means exactly that.
Related
i am a newbie in ruby... I'm trying to convert media into a scorm package using what i found on github but i got an error while trying to run the script in the command prompt undefined method `gsub' for nil:NilClass. I guess it may be due to a defined method. any idea on how i can remove this error ?
dir = ARGV.shift.gsub(/\/+$/, '')
index = nil
media = []
Dir["#{dir}/media/*.json"].each do |file|
id = JSON.parse(File.read(file))
base = file.gsub(/\/media\/.*\.json$/, '')
index = "#{base}/index.html"
name = File.basename file
media.push [name,id]
puts "#{name}: #{id}"
end
As the error says, you are calling the method gsub on an object that is an instance of NilClass, in other words you are calling gsub on nil.
The error message tells you in which method and on which line this happens and how you got to that line of code. You will have to examine the error message to find the place in your code where you are calling gsub on an object that is nil, then you have to examine your code to find out why that object is nil instead of a String as you expect it to.
I'm trying to run this code"
FACTORY = %w(ProcessedTransaction Chargeback).freeze
FACTORY.constantize.each do |factory|
factory.public_send(:delete_all)
end
end
But I get this error: NoMethodError: undefined methodconstantize' for #`
Do you know how I can solve the issue?
In ruby uppercased variables are constants by default so you can't call constantize on it. In your case it's just an array so this should work:
FACTORY = %w(ProcessedTransaction Chargeback).freeze
FACTORY.each do |factory|
factory.constantize.public_send(:delete_all)
end
You can call String#constantize only on strings but you are calling it on array FACTORY.
Remove FACTORY.constantize and add factory.constantize.public_send(:delete_all)
Also make sure you have ActiveSupport::Inflector required
Ruby has a fatal exception, but there is no guidance on how to raise it and I cannot figure it out. How do I raise a fatal exception in Ruby?
Sure you can.
Try this
FatalError = ObjectSpace.each_object(Class).find { |klass| klass < Exception && klass.inspect == 'fatal' }
And then
raise FatalError.new("famous last words")
How does this work?
fatal is an internal class without associated top-level constant
ObjectSpace.each_object(Class) enumerates over all classes
find { ... } finds an exception class named "fatal"
NB though, despite its name fatal is not special, it can be rescued. If you are looking for a way to end your program maybe best call the global exit method?
begin
raise FatalError.new
rescue Exception => e
puts "Not so fatal after all..."
end
Short answer is, you can, but probably shouldn't. This exception is reserved for Ruby internals. It is effectively hidden to users by being a constant with an all lowercase identifier. (Ruby won't do a constant lookup unless the identifier starts with an uppercase character.)
fatal
NameError: undefined local variable or method `fatal' for main:Object
The same is true when using Object#const_get:
Object.const_get(:fatal)
NameError: wrong constant name fatal
If this exception class was intended for us to use, then it would be readily available, and not hidden away.
I am learning Ruby and encountered the fail keyword. What does it mean?
if password.length < 8
fail "Password too short"
end
unless username
fail "No user name set"
end
In Ruby, fail is synonymous with raise. The fail keyword is a method of the Kernel module which is included by the class Object. The fail method raises a runtime error just like the raise keyword.
The fail method has three overloads:
fail: raises a RuntimeError without an error message.
fail(string): raises a RuntimeError with the string argument as an error message:
fail "Failed to open file"
fail(exception [, string [, array]]): raises an exception of class exception (first argument) with an optional error message (second argument) and callback information (third argument).
Example: Assume you define a function which should fail if given a bad argument. It is better to raise an ArgumentError and not a RuntimeError:
fail ArgumentError, "Illegal String"
Another Example: You can pass the whole backtrace to the fail method so you can access the trace inside the rescue block:
fail ArgumentError, "Illegal String", caller
caller is a Kernel method which returns the backtrace as an array of strings in the form file:line: in 'method'.
With no arguments, raises the exception in $! or raises a RuntimeError
if $! is nil. With a single String argument, raises a RuntimeError
with the string as a message. Otherwise, the first parameter should be
the name of an Exception class (or an object that returns an Exception
object when sent an exception message). The optional second parameter
sets the message associated with the exception, and the third
parameter is an array of callback information. Exceptions are caught
by the rescue clause of begin...end blocks.
Source: Ruby Documentation on the Kernel Module.
Rubocop says about usage of both words;
'Use fail instead of raise to signal exceptions.'
'Use raise instead of fail to rethrow exceptions.'
Here is an example.
def sample
fail 'something wrong' unless success?
rescue => e
logger.error e
raise
end
fail == raise
In other words, fail is just a popular alias for raise error-raising method. Usage:
fail ArgumentError, "Don't argue with me!"
www.ruby-doc.org is your friend. When I googled rubydoc fail "Kernel" was the first hit. My advice is, when in doubt, go to the definitive source for definitional stuff like this.
I have a test class:
require File.dirname(__FILE__) + '/../car.rb'
class CarTest < Test::Unit::TestCase
def test_set_color
assert_raise InvalidColorEntry "Exception not raised for invalid color" do
Car.set_color("not a color")
end
end
end
InvalidColorEntry is an exception class that I placed in the car.rb file like so:
class InvalidColorEntry < Exception; end
class Car
...
end
When I run the test, ruby is telling me that "InvalidColorEntry" is an undefined method. I have even tried to include the exception class definition in the test file even though I do not want to do that.
How can I make my test file aware of the custom exception definition? It obviously sees the car.rb file because it is able to call Car.set_color
Thanks!
It thinks InvalidColorEntry is supposed to be a method because you do InvalidColorEntry "Exception not raised for invalid color", which it parses as InvalidColorEntry("Exception not raised for invalid color").
I think you're just missing a comma after InvalidColorEntry.