Ruby: Nomethoderror, But Why

Ruby: NoMethodError, but why?

You have defined an instance method and are trying to call it as a method of a class. Thus you need to make the method hello a class method, not an instance method of the class Methods.

class Methods
def self.hello(player)
print "Hello, " << player
end
hello("Annie")
end

Or, if you want to define it as instance method then call it as below :

class Methods
def hello(player)
print "Hello, " << player
end
end
Methods.new.hello("Annie")

NoMethodError when there is a method

You must call like this:

die = Die.new
die.output # => 1
die.roll
die.output # => 3

First you need to instantiate the object (Die.new) into a variable (die).
Then call your method on it.

Note: better to use rand(1..6)

Without using a variable, the better you can do is:

Die.new.output # => 3

It is not possible chain methods as you did (or follow the answer by Martin Zinovsky)

NoMethodError in Welcome#show

You have defined @courses_user = CoursesUser.all, so its a collection not a single object. And you can't call complete! on a collection, so is the error.

Solution:

Iterate through @courses_user and call complete! on each instance like so

<% @courses_user.each do |cu| %>
<% if cu.complete! %>
<%= link_to "Completed", course, class: "block text-lg w-full text-center text-white px-4 py-2 bg-green hover:bg-green-dark border-2 border-green-dark leading-none no-underline" %>
<% else %>
<%= link_to "View Modules", course, class: "block text-lg w-full text-center text-grey-dark hover:text-darker px-4 py-2 border-2 border-grey leading-none no-underline hover:border-2 hover:border-grey-dark" %>
<% end %>
<% end %>

Note:

To avoid another potential error, you should change complete! to completed! as there is no method as complete! in your CoursesUser model.

So the final code would be

<% @courses_user.each do |cu| %>
<% if cu.completed! %>
<%= link_to "Completed", course, class: "block text-lg w-full text-center text-white px-4 py-2 bg-green hover:bg-green-dark border-2 border-green-dark leading-none no-underline" %>
<% else %>
<%= link_to "View Modules", course, class: "block text-lg w-full text-center text-grey-dark hover:text-darker px-4 py-2 border-2 border-grey leading-none no-underline hover:border-2 hover:border-grey-dark" %>
<% end %>
<% end %>

Ruby - NoMethodError, but why only sometimes?

There is basically an error on Reddit's side. I've written a work-around, but it sometimes has a small delay; it tries over and over until it succeeds. Edited to (mostly) match your original code.

require 'net/http'
require 'rubygems'
require 'json'

# Pull json file, parse out comments
url = 'https://www.reddit.com/r/askreddit/comments.json?sort=top&t=all&limit=100'
uri = URI(url)
error = true
while error
response = Net::HTTP.get(uri)
json = JSON.parse(response)
error = json["error"]
end

comments = json.dig("data", "children").map { |child| child.dig("data", "body") }

#Split words into array
words = comments.to_s.split(/[^'\w]+/)

words.delete_if { |a,_| a.length < 5}

#count and sort words
count = Hash.new(0)
words.each { |word| count.store(word, count[word]+1)}
count.delete_if { |_,b| b < 4}
sorted = count.sort_by { |word,count| count}.reverse
puts sorted

Rails NoMethodError when calling a method from a constant

Generally, dynamic constant assignment is discouraged in Ruby. Why would you want to define a constant that can possibly change within the life-cycle of an object? We don't know exactly what get_details is doing, but what is the use case of creating an instance method that is called from a constant as well as exposing the method? We can only assume return value is dynamic at this stage. Rubocop is also going arrest you for not freezing the constants, which is bad as linters are a good tool to abide by.

Constants can be changed and there is no way to avoid this as variables in Ruby are not containers: they point towards an object. However, it is your duty to make your code readable. If you see a constant that you cannot easily discern the value of, would you think that is readable?

We should talk about how Ruby loads constants and, more generally, files. Every Ruby application has its entry point. The interpreter will need the file to load and execute the commands of the application. The Ruby interpreter will increment over each statement inside your file and execute them following a specific set of rules, until it parses the entire file. What happens when the interpreter iterates to a constant? What other types of constants are there? Hint: CONSTANT_HERE is not the only constant you are defining.

The class keyword is processed first and the interpreter creates a constant 'TestingA' and stores in that constant a class object. The name of the class instance is "TestingA", a string, named after the constant. Yes, classes and modules are constants. Each class has a constant table, which is where "TestingA" will be stored. After this, the body of the class is interpreted and a new entry is created in the constant table for "CONSTANT_HERE" and the value is set and stored. This is happening before your definition of get_details has been defined: the interpreter wants to set the value, to store it, before "get_details" has been interpreted, which is why you are experiencing the error you are.

Now we know this, and wanting to provide an example of how constants are evaluated in code, you would need to mimic the below in order to have a method defined in a constant:

def get_details(file)
"stub_return"
end

class TestingA
CONSTANT_HERE = { details: get_details('example.json') }
end

In my opinion, the above is not good practise as it is an example mis-use of constant assignment. If you want to get details from a file, define a class/method and call the API/method instead. It's neater, assigns role of responsibility and is less ambiguous.

in `_main': undefined method `run' for nil:NilClass (NoMethodError)

At the point where you call request.run the value for request is nil. This is why you are seeing the error you're given.

This is happening because the line right above it assigns the nil value to the request variable.

You are clearly coming from another language that is not Ruby (some type of C maybe?), by how you've formatted things. It would help for you to get more familiar with Ruby and its idioms. However, best I can tell, you want to do something like this instead:

def _main
request = MySqliteRequest.new
request.from('nba_player_data.csv')
request.select('name')
request.where('birth_state', 'Indiana')
request.run
end
_main()

This assumes you've also defined (and in some cases probably overridden) these methods on your MySqliteRequest Object or Model:

from

select

where

However, please note that the way you're going about this is just completely against how Ruby and Ruby on Rails is designed to work.

Ruby: NoMethodError: undefined method when Mutating Instance Variable

NoMethodError: undefined method `reshuffle_count='

That means you are missing a setter. You have the getter defined def reshuffle_count but no setter.

class MagicBus < Array

attr_writer :seating

def seating
@seating || []
end

def reshuffle_count=(value)
@reshuffle_count=value
end

def reshuffle_count
@reshuffle_count || 0
end
.....

Or as @tadman pointed out, attr_writer :resuffle_count

ruby class undefined method (NoMethodError)

self refers to the class itself in a class method or to the current object in an instance method. In your case it refers to WordGame, the object's class.

If you really want it to refer to 30 into the factors method you have to define it as an instance method, because called on an object (30), not a class (Integer), opening the Integer class

class Integer
def factors
(1..self).select { |n| (self % n).zero? }
end
end

I think you know the alternative:

def self.factors(x)
(1..x).select { |n| (self % n).zero? }
end

def self.convert(number)
factors(number).map(&:to_s).each.map { |char| WORDGAME_MAP[char] }.join
end

Or better, with OOP.

class WordGame
def initialize(n)
@n = n
end

def convert
factors.map(&:to_s).each.map { |char| WORDGAME_MAP[char] }.join
end

private

def factors
(1..@n).select { |m| (@n % m).zero? }
end
end

Wordgame.new(30).convert


Related Topics



Leave a reply



Submit