'require' not loading ANY file - strange error message - ruby - ruby

Expected result: call on another file in the same dir with information
that will apply to current file
FILE TO BE CALLED ON:
(Location: C:\require\class.rb)
class Member
##count = 0
def initialize
##count =+ 1
end
def self.count
##count
end
end
Bob = Member.new
puts Member.count
OUTPUT: A new member is made, the total member count is +1
FILE DOING THE CALLING:
(Location: C:\require\require.rb)
require "./class.rb"
Henry = Member.new
puts Member.count
RESULT: No new member is made, the class is not called, apparently Ruby is looking in different directories (I suppose) even though both filesare right there next to each other in the directory C:\require
(I've set up this whole thing to simplify it, so I can show stack overflow the problem without any unnecessary fluff)
C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in
`require': cannot load such file -- ./class.rb (LoadError)
from C:/Ruby24-x64/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in
`require'
from C:/require/require.rb:1:in `<main>'
I'm only about 150 hours a developer. I apologize if this is a dumb question but I've exhausted my resources. It seems to work for everybody in every tutorial I watch flawlessly, so I'm quite dumbfounded. Thanks.
P.S. I'm using the Atom text editor (the output comes from pressing Alt + R, for those familiar)

Related

"ArgumentError (wrong number of arguments (given 2, expected 1))" for a simple Ruby function

So I'm writing a simple Ruby program, essentially a simple ORM. On my "delete" method, I have written the following:
file = "/Users/john/Projects/csv-orm/20180922-test.csv"
def delete id
counter = 0
csv = []
CSV.foreach(file) do |row|
counter += 1
if counter != id
csv << row
end
end
counter = 0
CSV.foreach(file, "w") do |row|
row = csv[counter]
end
end
delete 2
...and I'm running it in an irb session on my terminal (Mac OS X 10.13, ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]) to test it (for example, by pasting in the code above, and then trying delete 2, where the number 2 is the argument passed in for the id parameter), and I get the following error:
Traceback (most recent call last):
4: from /Users/apickle/.rvm/rubies/ruby-2.5.1/bin/irb:11:in `<main>'
3: from (irb):23
2: from (irb):19:in `delete'
1: from /Users/apickle/.rvm/rubies/ruby-2.5.1/lib/ruby/2.5.0/csv.rb:1139:in `foreach'
ArgumentError (wrong number of arguments (given 2, expected 1))
Just to get it out of the way, I have tried testing it in a freshly exited and reopened irb session, and I am typing in require "csv" when I start it up. I'm not sure what to do. :/
EDIT: I've renamed the function to destroy and flfllgpt, and I get the same result - and I have made a simple function that takes a single integer named id and putss it. That function works. It seems to be somehow related to the CSV calls... when I comment those blocks out, it doesn't throw that to me. But I've used them before, too!
It is hard to diagnose the problem without the exact error message, which includes the line number where the error occurs, the method in which the error occurs, the method call for which the error occurs, and the stack trace.
However, there is exactly one place in the code you posted where a method is called with 2 arguments:
CSV.foreach(file, "w") do |row|
# …
end
And indeed, the documentation for CSV::foreach clearly says that CSV::foreach only takes one positional argument, this must be the culprit. There simply is no other place in your code that could possibly raise this exception.
I guess CSV.foreach(file, "w") is the culprit here, because I think what you want to do is open a new file and then write the result? Check this out: https://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html#method-c-foreach
If changing it does not help, can you post the full error message? That makes it easier to identify the error.

Ruby require_relative executing script?

I'm working on a game server in ruby, and during testing I'm having trouble testing components individually. I wasn't getting output from my launcher, just the server, so I commented out the initialisation of the server- yet eclipse still showed output from the server!
I then went to the command line, assuming eclipse was looking at the wrong file (git has messed it around before, but as you can see, the stack trace shows that Server.rb is being executed in its entirety from line 5: require_relative 'Server':
This is the text content of the file:
class Launcher
puts "File saved at #{File.mtime($0)}"
require_relative 'Server'
require_relative 'Game'
#STDOUT.sync = true
puts "Launcher started"
#server = Server.new
print "server made"
game = Game.new
#serverThread = Thread.new{server.start()}
gameThread = Thread.new{game.start()}
while (running)
print "Stop? "
input = gets.chomp
if (input.equals?("yes"))
running = false
end
end
server.stop
game.stop
gameThread.join
serverThread.join
end
and the terminal output:
C:\Users\gossfunkel\git\citadelserver\RubyCitadelServer>ruby Launcher.rb
File saved at 2013-06-22 18:16:44 +0100
Server starting up at 2013-06-22 18:16:47 +0100...
C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:20:in `recvfro
m': Interrupt
from C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:2
0:in `run'
from C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:1
5:in `start'
from C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:3
0:in `<class:Server>'
from C:/Users/gossfunkel/git/citadelserver/RubyCitadelServer/Server.rb:1
:in `<top (required)>'
from Launcher.rb:5:in `require_relative'
from Launcher.rb:5:in `<class:Launcher>'
from Launcher.rb:1:in `<main>'
How do I require a file without this happening, and should it be?
I can't tell without seeing the classes, but I would guess that either
game.start is doing more than you thought, and is starting the server for itself
You are, as your subject line suggests, running a different file from the one you are editing (or not saving the file once it is changed). Check by putting an obvious puts at the top of the program. Something like
puts "File saved at #{File.mtime($0)}"
should do the trick
After discussion, it seems there's a third option. The code in Server.pm creates and runs a server as well as defining the class. You need to remove the require as well as the lines that use the Server class.

Trouble Creating Directories with mkdir

New to Ruby, probably something silly
Trying to make a directory in order to store files in it. Here's my code to do so
def generateParsedEmailFile
apath = File.expand_path($textFile)
filepath = Pathname.new(apath + '/' + #subject + ' ' + #date)
if filepath.exist?
filepath = Pathname.new(filepath+ '.1')
end
directory = Dir.mkdir (filepath)
Dir.chdir directory
emailText = File.new("emailtext.txt", "w+")
emailText.write(self.generateText)
emailText.close
for attachment in #attachments
self.generateAttachment(attachment,directory)
end
end
Here's the error that I get
My-Name-MacBook-2:emails myname$ ruby etext.rb email4.txt
etext.rb:196:in `mkdir': Not a directory - /Users/anthonydreessen/Developer/Ruby/emails/email4.txt/Re: Make it Brief Report Wed 8 May 2013 (Errno::ENOTDIR)
from etext.rb:196:in `generateParsedEmailFile'
from etext.rb:235:in `<main>'
I was able to recreate the error - it looks like email4.txt is a regular file, not a directory, so you can't use it as part of your directory path.
If you switched to mkdir_p and get the same error, perhaps one of the parents named in '/Users/anthonydreessen/Developer/Ruby/emails/email4.txt/Re: Make it Brief Report Wed 8 May 2013' already exists as a regular file and can't be treated like a directory. Probably that last one named email.txt
You've got the right idea, but should be more specific about the files you're opening. Changing the current working directory is really messy as it changes it across the entire process and could screw up other parts of your application.
require 'fileutils'
def generate_parsed_email_file(text_file)
path = File.expand_path("#{#subject} #{date}", text_file)
while (File.exist?(path))
path.sub!(/(\.\d+)?$/) do |m|
".#{m[1].to_i + 1}"
end
end
directory = File.dirname(path)
unless (File.exist?(directory))
FileUtils.mkdir_p(directory)
end
File.open(path, "w+") do |email|
emailText.write(self.generateText)
end
#attachments.each do |attachment|
self.generateAttachment(attachment, directory)
end
end
I've taken the liberty of making this example significantly more Ruby-like:
Using mixed-case names in methods is highly irregular, and global variables are frowned on.
It's extremely rare to see for used, each is much more flexible.
The File.open method yields to a block if the file could be opened, and closes automatically when the block is done.
The ".1" part has been extended to keep looping until it finds an un-used name.
FileUtils is employed to makes sure the complete path is created.
The global variable has been converted to an argument.

Moving image to another folder

currently reading Learn To Program. Im at page 91-92 where you create a program that moves images from your USB drive to desired location and changing the name of each image. But i get the follwing error when runing the program. Using Ubuntu as you can tell, but get "Invalid cross-device link". Any ideas of how to solve this?
pierre#ubuntu:~/ruby$ ruby move.rb
What would you like to call this batch?
IMG
Downloading 1 files: .move.rb:36:in `rename': Invalid cross-device link - (/media/SanDisk Cruzer Blade/pictures/UMG.jpg, IMG01.jpg) (Errno::EXDEV)
from move.rb:36:in `block in <main>'
from move.rb:17:in `each'
from move.rb:17:in `<main>'
This is the code
# Heres where the pictures are stored
Dir.chdir '/home/pierre/Skrivbord'
# First we find all of the pictures to be moved
pic_names = Dir['/media/SanDisk Cruzer Blade/pictures/**/*.{JPG,jpg}']
puts 'What would you like to call this batch?'
batch_name = gets.chomp
puts
print "Downloading #{pic_names.length} files: "
# This will be our counter. We'll start at 1 today,
# though normally I like to count from 0.
pic_number = 1
pic_names.each do |name|
print '.' # This is our "progress bar".
new_name = if pic_number < 10
"#{batch_name}0#{pic_number}.jpg"
else
"#{batch_name}#{pic_number}.jpg"
end
# This renames the picture, but since "name" has a big long
# path on it, and "new_name" doesn't, it also moves the file to the current
# working directory, which is now Katy's PictureInbox folder. Since it's a
# *move*, this effectively downloads and deletes the originals. And since this
# is a memory card, not a hard drive, each of these takes a second or so; hence,
# the little dots let her know that my program didn't hose her machine.
# (Some marriage advice from your favourite author/programmer: it's all about
# the little things.)
# Now where were we? Oh, yeah...
File.rename name, new_name
# Finally, we increment the counter.
pic_number = pic_number + 1
end
puts # This is so we aren't on progress bar line.
puts 'Done, cutie!'
.. you are trying to use "rename" to physically move a file, and the system is objecting
to this misconception. File.rename can only rename files, it cannot
move them. It works only on one storage device/volume/whatever.
require 'fileutils'
include FileUtils
cp(old, new )
rm (old)
http://www.ruby-forum.com/topic/78627

Why am I getting NoMethodError from IRB for my own Module and method

I have taken this example exactly from the Ruby Cookbook. Unfortunately for me, like a whole lot of the examples in that book, this one does not work:
my file (Find.rb - saved both locally and to Ruby\bin):
require 'find'
module Find
def match(*paths)
matched=[]
find(*paths) { |path| matched << path if yield path }
return matched
end
module_function :match
end
I try to call it this way from IRB, according to the example the book provides:
irb(main):002:0> require 'Find'
=> false
irb(main):003:0> Find.match("./") { |p| ext = p[-4...p.size]; ext && ext.downcase == "mp3" }
It SHOULD return a list of mp3 files in my recursive directory. Instead, it does this:
NoMethodError: undefined method `match' for Find:Module
from (irb):3
from C:/Ruby192/bin/irb:12:in `<main>'
What gives? I'm new at this (although I MUST say that I'm farther along with Python, and much better at it!).
How can I get IRB to use my method?
I ran into this with irb on a Mac running Snow Leopard while using the default version of ruby (and irb of course) installed with OS X. I was able to get past it by including the module in IRB after loading the module or in the file after the module definition.
include module_name
I'm not sure if this is a defect or known behavior.
The only explanation is that the code you posted is not the code you are running, since both carefully reading it and simply cut&paste&running it shows absolutely no problems whatsoever.
What directory are you calling IRB from? Try calling it from the directory where your find.rb file is located. Also, I don't know if it makes any difference but convention is to name the file the lowercase version of the module / class. So the module would be Find and the file name would be find.rb. You shouldn't need the require call in the file itself.
So, start your command prompt window, cd into the directory that contains find.rb and run irb. In IRB you should be able to require "find" and it should return true. From there you should be able to call Find.match.
I know this question is already 3 years old, but since this is the first hit on google for the problem, and I had been banging my head against the wall all afternoon with the same problem doing the tutorial here: http://ruby.learncodethehardway.org/book/ex25.html, here goes: the function definition in the module should read
module Find
def Find.match(*paths)
...
end
end

Resources