run a ruby project on ruby mine - ruby

i am new to ruby programming. i wrote a little program to recursively count blobs in a two dimensional array. it contains two classes, cell and blobs. i am getting the following error and i dont know what it means or how to fix it.
attached is my code and the error.
Cell Class
class Cell
attr_accessor :data,:visited,:row,:col
def initialize(data, row, col)
#data = data
#visited = false
#row = row
#col = col
end
def to_s
self.data.to_s
end
end
Blob class
class Blobs
require ./Cell
#cells = Array.new(10){Array.new(10)}
def separate(percentage)
for i in 0..10
for i in 0..10
random = Random.rand(0,100)
if random < percentage
#cells[i][j] = Cell.new('x',i,j)
else
#cells[i][j] = Cell.new(nil, i, j)
end
end
end
end
def markBlob(currentCell)
if currentCell.visited
return
end
currentCell.visited = true
if currentCell.data.nil?
return
end
if currentCell.row >0
markBlob(#cells[currentCell.row-1][currentCell.col])
end
if currentCell.row <#cells.size-1
markBlob(#cells[currentCell.row+1][currentCell.col])
end
if currentCell.col>0
markBlob(#cells[currentCell.row][currentCell.col-1])
end
if currentCell.col<#cells.size-1
markBlob(#cells[currentCell.row][currentCell.col+1])
end
end
def countblobs
count = 0
for i in 0..10
for j in 0..10
cell = #cells[i][j]
if !cell.visited && cell.data.nil?
count++
markBlob(cell)
end
end
end
return count
end
def to_s
for i in 0..10
for j in 0..10
if #cells[i][j].data.nil?
puts '- '
else
puts #cells[i][j].data + ' '
end
end
puts "\n"
end
end
blob = Blobs.new
number = blob
puts number
end
this is the error i am getting:
C:\Ruby22\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:/Users/Nechama/RubymineProjects/blobs/blobs.rb
C:/Ruby22/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:38:in `require': wrong number of arguments (0 for 1) (ArgumentError)
from C:/Users/Nechama/RubymineProjects/blobs/blobs.rb:3:in `<class:Blobs>'
from C:/Users/Nechama/RubymineProjects/blobs/blobs.rb:2:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
Process finished with exit code 1

require should get string as an argument.
Use require_relative to cell file
require_relative 'cell'
and put it above class Blobs.
More about Including Other Files In Ruby

Related

Can I instantiate a class from a method within another class? (Ruby)

I've redone the question and included the full code for both files. In the touch_in method I am trying to instantiate a Journey class in the variable called 'journey'.
require_relative 'journey'
class Oystercard
MAXIMUM_BALANCE = 90
MINIMUM_BALANCE = 1
MINIMUM_CHARGE = 1
def initialize
#balance = 0
#journeys = {}
end
def top_up(amount)
fail 'Maximum balance of #{maximum_balance} exceeded' if amount + balance > MAXIMUM_BALANCE
#balance += amount
end
def in_journey?
#in_journey
end
def touch_out(station)
deduct(MINIMUM_CHARGE)
#exit_station = station
#in_journey = false
#journeys.merge!(entry_station => exit_station)
end
def touch_in(station)
fail "Insufficient balance to touch in" if balance < MINIMUM_BALANCE
journey = Journey.new
#in_journey = true
#entry_station = station
end
attr_reader :journeys
attr_reader :balance
attr_reader :entry_station
attr_reader :exit_station
private
def deduct(amount)
#balance -= amount
end
end
The Journey file is as follows:
class Journey
PENALTY_FARE = 6
MINIMUM_CHARGE = 1
def initialize(station = "No entry station")
#previous_journeys = {}
end
def active?
#active
end
def begin(station = "No entry station")
#active = true
#fare = PENALTY_FARE
#entry_station = station
end
def finish(station = "No exit station")
#active = false
#fare = MINIMUM_CHARGE
#exit_station = station
#previous_journeys.merge!(entry_station => exit_station)
end
attr_reader :fare
attr_reader :previous_journeys
attr_reader :entry_station
attr_reader :exit_station
end
I think that the 'touch_in' method should create a 'journey' variable that I called methods on, such as 'finish(station)' or 'active?' etc. When I attempt to do this in IRB I am given the following error:
2.6.3 :007 > journey
Traceback (most recent call last):
4: from /Users/jamesmac/.rvm/rubies/ruby-2.6.3/bin/irb:23:in `<main>'
3: from /Users/jamesmac/.rvm/rubies/ruby-2.6.3/bin/irb:23:in `load'
2: from /Users/jamesmac/.rvm/rubies/ruby-2.6.3/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
1: from (irb):7
NameError (undefined local variable or method `journey' for main:Object)
I'm aware that much of the code above is sloppily written and there are probably other bits, beside the 'journey' issue, where it's just incorrect. Please let me know if this is the case, the more I'm told the better.
Apologies to anyone who attempted to help me on my first attempt, as I say I'm still getting used to SO and was trying to make the post easier to read.
class Journey
# ...
def initialize
puts "Journey initialized"
# ...
end
# ...
end
require_relative 'journey'
class Oystercard
def initialize
end
# ...
def touch_in(station)
journey = Journey.new
# ...
end
end
Oystercard.new.touch_in("station")
stack_question$ ruby oystercard.rb
Journey initialized
It works fine - are you having some issue with this that is beyond the scope of the question?

ArgumentError on Ruby

I have been trying to run the Ruby code below but I keep on getting the following error:
Failed: ArgumentError: wrong number of arguments (given 1, expected 0)
stacktrace: ./basic_read_write.rb:3:in write_data_to_file'
/tmp/test.rb:5:inblock (2 levels) in
# writes the number of lines then each line as a string.
def write_data_to_file()
a_file=File.new("mydata.txt","w")
a_file.puts('5')
a_file.puts('Fred')
a_file.puts('Sam')
a_file.puts('Jill')
a_file.puts('Jenny')
a_file.puts('Zorro')
a_file.close
end
def read_data_from_file()
a_file=File.new("mydata.txt","r")
count = a_file.gets.to_i
puts count.to_s
for i in 0..count.to_i
puts a_file.gets
end
a_file.close
def main
# open for writing
write_data_to_file()
# open for reading
read_data_from_file()
end
main
end
The above code looks good except for the end statement in the methods. Every method ends with end.
According to your code, the def read_data_from_file() has an end at the end after the def main.
def write_data_to_file()
a_file=File.new("mydata.txt","w")
a_file.puts('5')
a_file.puts('Fred')
a_file.puts('Sam')
a_file.puts('Jill')
a_file.puts('Jenny')
a_file.puts('Zorro')
a_file.close
end
def read_data_from_file()
a_file=File.new("mydata.txt","r")
count = a_file.gets.to_i
puts count.to_s
for i in 0..count.to_i
puts a_file.gets
end
a_file.close
end
def main
# open for writing
write_data_to_file()
# open for reading
read_data_from_file()
end
main

How to have an object(class) be a parameter for another object(class) in Ruby

I am new to Ruby so I am not exactly sure what I am doing wrong or violating.
I have two classes in my example, Deliverable and Pillar.
A pillar object can contain one or more deliverables.
class Deliverable
def initialize (name, state, pillar)
#name = name
#state = state
#pillarNumber = pillar
end
def getName
#name
end
def state
#state
end
def pillarNumber
#pillarNumber
end
end
class Pillar
def initalize (name, mine)
#name = name
#mine = mine
end
def getName
#name
end
def getDeliverable
#mine
end
def getDeliverableName
#mine.getName
end
end
aDel = Deliverable.new("Deliverable", 0, 1)
puts "Deliverable Name: " + aDel.getName
aPil = Pillar.new("Pillar", aDel)
puts "Pillar Name: " + aPil.getName + "\n"
When I run this code I get this error:
pillar.rb:46:in `initialize': wrong number of arguments (2 for 0) (ArgumentError)
from pillar.rb:46:in `new'
from pillar.rb:46:in `<main>'
Any advise on what I am doing wrong?
You mispelled the name of the constructor for Pillar
# ⇓ NOTE MISSED “i” HERE
def initialize (name, mine)

How does one create an object from a class within a gem?

Lets say you write a gem containing classes within a module. If one installs that gem and wishes to create an object instance from that class, how do they successfully do that in another rb document? Here is my gem class.
require "Sentencemate/version"
module Sentencemate
#Object used to emulate a single word in text.
class Word
def initialize(word)
#word = word
end
def append(str)
#word = #word << str
return #word
end
def get
return #word
end
def setword(str)
#word = str
end
def tag(str)
#tag = str
end
end
# Object used to emulate a sentence in text.
class Sentence
def initialize(statement)
#sentence = statement
statement = statement.chop
statement = statement.downcase
lst = statement.split(" ")
#words = []
for elem in lst
#words << Word.new(elem)
end
if #sentence[#sentence.length-1] == "?"
#question = true
else
#question = false
end
end
def addword(str)
#words << Word.new(str)
end
def addword_to_place(str, i)
#words.insert(i, Word.new(str))
end
def set_word(i, other)
#words[i].setword(other)
end
def [](i)
#words[i].get()
end
def length
#words.length
end
def addpunc(symbol)
#words[self.length-1].setword(#words[self.length-1].get << symbol)
end
def checkforword(str)
for elem in #words
if elem.get == str
return true
end
end
return false
end
end
end
in Rubymine, I will try the following in the Irb console:
/usr/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /usr/bin/irb --prompt simple
Switch to inspect mode.
>> require 'Sentencemate'
=> true
>> varfortesting = Sentence.new("The moon is red.")
NameError: uninitialized constant Sentence
from (irb):2
from /usr/bin/irb:12:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
What would be the proper way to be able to use the classes in the gem that I installed?
In your Sentence class
#words << Word.new(elem)
Word is resolved correctly because ruby looks in current namespace first (that being Sentencemate module).
Outside of that module, one has to use fully-qualified names, such as Sentencemate::Word. This is necessary to differentiate this Word from a dozen other Word classes user's app might have.

Recursive lambdas in Ruby

I have the following code which correctly generates all possible trees of size num:
class Tree
attr_accessor :left, :right
def initialize left = nil, right = nil
#left = left
#right = right
end
# Don't ever specify any arguments, it will make me very angry.
# Tilt your head 90 degrees to the side to see the tree when viewing.
def print level = 0
#right.pretty_print(level + 1) if #right
puts (' ' * level) + to_s
#left.pretty_print(level + 1) if #left
end
def self.generate num
trees = []
generate_subtrees(num) { |tree| trees << tree } if num > 0
trees
end
private
def self.generate_subtrees num, &block
if num == 0
yield nil
else
(1..num).each do |root_position|
generate_subtrees(root_position - 1) do |left|
generate_subtrees(num - root_position) do |right|
yield Tree.new nil, left, right
end
end
end
end
end
end
I’m trying to (for the sake of it) “condense” this into one method, utilizing lambda recursion. My current attempt (of several iterations) is below:
def self.generate num
trees = []
gen = ->(num, &block) do
if num == 0
yield nil # L61
else
(1..num).each do |root_position| # L63
gen.call(root_position - 1) do |left| # L64
gen.call(num - root_position) do |right|
block.call { Tree.new nil, left, right }
end
end
end
end
end
gen.call(num) { |tree| trees << tree } # L73
trees
end
This results in the error (referenced lines noted above):
LocalJumpError: no block given (yield)
from tree.rb:61:in `block in generate'
from tree.rb:64:in `call'
from tree.rb:64:in `block (2 levels) in generate'
from tree.rb:63:in `each'
from tree.rb:63:in `block in generate'
from tree.rb:73:in `call'
from tree.rb:73:in `generate'
from (irb):4
from /Users/amarshall/.rbenv/versions/1.9.2-p290/bin/irb:12:in `<main>'
What am I doing wrong? Alternative solutions to this mostly academic problem are also welcome.
The yield keyword does not work from inside a lambda. The alternative is to use &block, in the same way that you are already doing on line 64 and 65:
gen = ->(num, &block) do
if num == 0
block.call(nil)
else
# ...
end
gen.call(num) { |tree| trees << tree }

Resources