Error with virtual tree program ruby - ruby-on-rails

I have just started learning ruby and have made this program following a tutorial.
I keep getting an error when trying to run and can't find an answer.
The program is suppose to be able to pick fruit, count the fruit, give the height and grow.
C:\Sites\testfolder>ruby orangetree.rb
orangetree.rb:2:in `initialize': wrong number of arguments (1 for 0) (ArgumentEr
ror)
from orangetree.rb:51:in `new'
from orangetree.rb:51:in `<class:OrangeTree>'
from orangetree.rb:1:in `<main>'
C:\Sites\testfolder>
Here is the program
class OrangeTree
def initialize
#age = 0
#tall = 0
#fruit = 0
puts 'You have planted a new tree!'
def height
puts 'The tree is ' + #tall.to_s + 'foot tall.'
end
def pickAFruit
if #fruit <= 1
puts 'There is not enough fruit to pick this year.'
else
puts 'You pick an orange from the tree.'
#fruit = #fruit - 1
end
end
def countOranges
puts 'The tree has ' + #fruit.to_s + 'pieces of fruit'
end
def oneYearPasses
#age = #age + 1
#tall = #tall + 3
#fruit = 0
if dead?
puts 'The Orange Tree Dies'
exit
end
if #age > 2
#fruit = #age*10
else
#fruit = 0
end
end
private
def dead?
#age > 5
end
end
tree = OrangeTree.new 'tree'
command = ''
while command != 'exit'
puts 'please enter a command for the virual tree'
command = gets.chomp
if command == 'tree height'
tree.height
elsif command == 'pick fruit'
tree.pickAFruit
elsif command == 'wait'
tree.oneYearPasses
elsif command == 'count fruit'
tree.countOranges
elsif command == 'exit'
exit
else
puts 'Cant understand your command, try again'
end
end
end
Can anybody help?

You have some syntax errors. I have fixed them below. The syntax errors were:
You had an extra end on the last line (for closing the class declaration)
You were passing an argument to OrangeTree.new ("tree") that was unexpected. This is what the wrong number of arguments (1 for 0) error message in your question is referring to.
You were missing an end to close your initialize method declaration (after the puts 'You have planted a new tree!' line)
I have also fixed the indentation, which makes the code more readable and much easier to spot syntax errors like this.
class OrangeTree
def initialize
#age = 0
#tall = 0
#fruit = 0
puts 'You have planted a new tree!'
end
def height
puts 'The tree is ' + #tall.to_s + 'foot tall.'
end
def pickAFruit
if #fruit <= 1
puts 'There is not enough fruit to pick this year.'
else
puts 'You pick an orange from the tree.'
#fruit = #fruit - 1
end
end
def countOranges
puts 'The tree has ' + #fruit.to_s + 'pieces of fruit'
end
def oneYearPasses
#age = #age + 1
#tall = #tall + 3
#fruit = 0
if dead?
puts 'The Orange Tree Dies'
exit
end
if #age > 2
#fruit = #age*10
else
#fruit = 0
end
end
private
def dead?
#age > 5
end
end
tree = OrangeTree.new
command = ''
while command != 'exit'
puts 'please enter a command for the virual tree'
command = gets.chomp
if command == 'tree height'
tree.height
elsif command == 'pick fruit'
tree.pickAFruit
elsif command == 'wait'
tree.oneYearPasses
elsif command == 'count fruit'
tree.countOranges
elsif command == 'exit'
exit
else
puts 'Cant understand your command, try again'
end
end

Related

Ruby : Loop, Case and iterations problems ( Rock , Paper, Scissors )

I´m ruby student since 1 month and i´m stuck with one part of my code. The project is based on a game ( rock, paper, scissor) but i´m facing of a problem that i cannot solve for moment. I would like to add one parameters to this game especially when the user enter a wrong input by displaying a message but with the condition i added it´s not working.
elsif player_choice != 'r' || player_choice != 'p' || player_choice != 's' || player_choice != 'q' || player_choice != 'x'
puts "wrong input"
So if you have some advice or some hint to share with me it will be great ! ( see below the entire code ).
Thank you very much.
#intro
puts "***** WELCOME TO PAPER SCISSORS ROCKS GAME *****"
puts "Input p = Paper, r = Rocks, s = Scissors, x = Display your score , q = Quit the game. "
25.times { print "-" }
puts
#scores
playerScore = 0
cpuScore = 0
CHOICES = {'p' => 'Paper', 'r' => 'Rock', 's' => 'Scissors', 'x' => 'score','q' => 'quit' }
CHOICE_CPU = {'p' => 'Paper', 'r' => 'Rock', 's' => 'Scissors'}
loop do
# player picks
begin
puts "Select your pick: (p/r/s/x/q)"
player_choice = gets.chomp.downcase
end until CHOICES.keys.include?(player_choice)
# computer picks
cpu_choice = CHOICE_CPU.keys.sample
def throw_message(winning_choice)
case winning_choice
when 'p'
puts "Paper wraps Rock!"
when 'r'
puts "Rock smashes Scissors!"
when 's'
puts "Scissors cuts Paper!"
when 'x'
puts "Live score"
when 'q'
puts "you decide to quit the game"
end
end
#display scores
if player_choice == 'x'
throw_message(player_choice)
puts "PLAYER : #{playerScore} CPU : #{cpuScore}"
#quit the game
elsif player_choice == 'q'
throw_message(player_choice)
break
# tie result
elsif player_choice == cpu_choice
puts "It's a Tie ! "
#player win
elsif (player_choice == 'p' && cpu_choice == 'r') || (player_choice == 'r' && cpu_choice == 's') || (player_choice == 's' && cpu_choice == 'p')
throw_message(playe·r_choice)
puts "You Win"
playerScore +=1
#display invalid input
elsif player_choice != 'r' || player_choice != 'p' || player_choice != 's' || player_choice != 'q' ||
player_choice != 'x'
puts "wrong input"
#cpu win
else throw_message(cpu_choice)
puts "Computer Win"
cpuScore +=1
end
end
Move the CHOICES.keys.include?(player_choice) check to the top of the main if/else logic. If you validate your input as early as possible, the rest of the code can assume the input is good; there's no need to spell out all the possible choices again.
I'm using a case/when because it's easier to read than if/elsif. throw_message is defined outside the loop, inside the loop its being redefined repeatedly. And I've removed choices from throw_message which don't have to do with the game; this avoids repeating the full set of choices.
def throw_message(winning_choice)
case winning_choice
when 'p'
puts "Paper wraps Rock!"
when 'r'
puts "Rock smashes Scissors!"
when 's'
puts "Scissors cuts Paper!"
end
end
def player_wins?(player_choice, cpu_choice)
return player_choice == 'p' && cpu_choice == 'r') ||
player_choice == 'r' && cpu_choice == 's') ||
player_choice == 's' && cpu_choice == 'p')
end
loop do
# player picks
puts "Select your pick: (p/r/s/x/q)"
player_choice = gets.chomp.downcase
# cpu picks
cpu_choice = CHOICE_CPU.keys.sample
case
when !CHOICES.keys.include?(player_choice)
puts "wrong input"
when player_choice == 'x'
puts "Live score"
puts "PLAYER : #{playerScore} CPU : #{cpuScore}"
when player_choice == 'q'
puts "you decide to quit the game"
break
when player_choice == cpu_choice
puts "It's a tie!"
when player_wins?(player_choice, cpu_choice)
throw_message(player_choice)
puts "You Win"
playerScore +=1
else
throw_message(cpu_choice)
puts "Computer Win"
cpuScore +=1
end
end

NoMethodError in controller

Hello I'm new at Ruby and I'm trying to make a method in my Project controller like so:
def update_phase
#project = Project.find(params[:id])
diff = (Date.current.year * 12 + Date.current.month) - (#project.starting.year * 12 + #project.starting.month)
case
when diff >= 30
#project.process = 11
.
.
.
when diff >= 0
#project.process = 1
else
#project.process = 0
end
proc = #project.process.to_f
case
when proc >= 9
#project.phase = "Final"
when proc >= 5
#project.phase = "Desarrollo"
when proc >= 1
#project.phase = "Inicio"
else
#project.phase = "Error en el proceso"
end
end
starting is a timestamp in the model. In my view I have:
<% #project.update_phase %>
but I get the error: "NoMethodError in Projects#show"
how can I fix this?
Depending on what's or where does starting come from, you could use a before_save callback, this way everytime you're going to create a new record, it triggers the update_phase method and assigns the values for process and phase from the current project object:
class Project < ApplicationRecord
before_save :update_phase
...
def update_phase
diff = (Date.current.year * 12 + Date.current.month) - (self.starting.year * 12 + self.starting.month)
case
when diff >= 30
self.process = 11
...
end
proc = self.process.to_f
case
when proc >= 9
self.phase = 'Final'
...
end
end
end

How to have an ouput without symbols and quotations etc. in Ruby

In this particular code when the input[0] = "status", I want the output to remove the symbols "" [] and , but I can't seem to find the solution, I've tried using each but I think what I'm doing is wrong, and I'm new to Ruby please help. Thanks!
class Main
puts "Welcome to the automated Parking Lot"
start = true
parking_lot = []
allocated_slot = 0
slot_number = 0
plate_number = ""
color = ""
x = ""
while (start == true) do
parking = Array.new
input = gets.split(' ')
case input[0]
when input[0] = "create_parking_lot"
parking_lot.clear
allocated_slot = input[1]
puts "Created a parking lot with #{allocated_slot} slots."
when input[0] = "park"
plate_number = input[1]
color = input[2]
if parking_lot.length < allocated_slot.to_i
slot_number = slot_number + 1
parking = [slot_number, input[1], input[2]]
parking_lot.push(parking)
parking_lot.sort!
puts "Allocated slot number: #{slot_number}"
else
puts "Sorry, parking lot is full"
end
when input[0] = "leave"
slot_number = input[1].to_i
puts "Slot number #{slot_number} is now free."
slot_number = slot_number - 1
parking_lot.delete_at(slot_number)
parking_lot[slot_number]
#puts parking_lot
when input[0] = "quit"
break
when input[0] = "status"
if parking_lot.count == 0
puts "No cars are parked."
else
puts "Slot No. Registration No. Color"
parking.sort!
i = 0
y = ""
while i < allocated_slot.to_i do
x = parking_lot[i].to_s
y = x.split(' ')
puts "#{y[0]} #{y[1]} #{y[2]}" #
#y.each { |a| print a, " " }
i = i+1
end
end
when input[0] = "registration_numbers_for_cars_with_color"
puts "registration number for cars"
when input[0] = "slot_numbers_for_cars_with_color"
puts "slot number for cars with color"
when input[0] = "slot_number_for_registration_number"
puts "slot number for registration number"
when input[0] = "check"
puts parking_lot
else
puts "Command Error"
end
end
and the output goes like this:
[1, "HA-312424242", "Green"]
If you have an array being outputted that looks like this:
[1, "HA-312424242", "Green"]
Then you can call the join method on it like this:
[1, "HA-312424242", "Green"].join(' ')
and it will produce:
"1 HA-312424242 Green"

Can I build an array using a loop in Ruby?

I just started learning Ruby/Rails, and am trying to write a program that builds an array, then formats the new array.
It works up to the second while, and, if I have an array already built, the second part works as well. Is there something I am leaving out?
chap = []
page = []
lineWidth = 80
x = 0
n = chap.length.to_i
puts 'chapter?'
chapter = gets.chomp
while chapter != ''
chap.push chapter
puts 'page?'
pg = gets.chomp
page.push pg
puts 'chapter?'
chapter = gets.chomp
end
puts ('Table of Contents').center lineWidth
puts ''
while x < n
puts ('Chapter ' + (x+1).to_s + ' ' + chap[x]).ljust(lineWidth/2) +(' page ' + page[x]).rjust(lineWidth/2)
x = x + 1
end
Thanks for your help!
Simple pilot error: You called
n = chap.length.to_i
too early. You have to get the length of the chap list AFTER you put things in it. Move that line here:
...
puts 'chapter?'
chapter = gets.chomp
end
n = chap.length.to_i
puts ('Table of Contents').center lineWidth
and it works fine.

Rails - Simple Loop Not Working

In my controller I am trying to do a bulk insert into a table, in my first attempt it works but the names somehow get mangled as the following: (loop runs 24 times which is what I want)
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11
test-port-name-0-1-2-3-4-5-6-7-8-9-10
test-port-name-0-1-2-3-4-5-6-7-8-9
test-port-name-0-1-2-3-4-5-6-7-8
test-port-name-0-1-2-3-4-5-6
test-port-name-0-1-2-3-4-5-6-7
test-port-name-0-1-2-3-4-5
test-port-name-0-1-2-3-4
test-port-name-0-1-2
test-port-name-0-1-2-3
test-port-name-0
test-port-name-0-1
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23
instead of test-port-name-0 .... test-port-name-23
def bulk_port_import
if request.post?
#attempt create
count = 0
for i in 1..session[:no_ports]
params[:dp][:name] = params[:dp][:name] + '-' + count.to_s
#dp = DevicePort.create params[:dp]
count = count + 1
end
end
#success = "Saved." if #dp.valid?
#error = ""
#dp.errors.each_full {|e| #error += e + ", "}
redirect_to '/device/update/' + params[:dp][:device_id]
end
Different attempt:
def bulk_port_import
if request.post?
#attempt create
i = 0
while i < session[:no_ports] do
params[:dp][:name] = params[:dp][:name] + '-' + i.to_s
#dp = DevicePort.create params[:dp]
i++
end
end
session.delete(:no_ports)
#success = "Saved." if #dp.valid?
#error = ""
#dp.errors.each_full {|e| #error += e + ", "}
redirect_to '/device/update/' + params[:dp][:device_id]
end
but with this I get syntax error, unexpected kEND and I can't see what I'm doing wrong in either case, it's probably something stupid, again.
Its because you are changing params[:dp][:name] in the loop
def bulk_port_import
if request.post?
#attempt create
count = 0
for i in 1..session[:no_ports]
dp_name = params[:dp][:name] + '-' + count.to_s
#dp = DevicePort.create(params[:dp].merge(:name => dp_name))
count = count + 1
end
end
#success = "Saved." if #dp.valid?
#error = ""
#dp.errors.each_full {|e| #error += e + ", "}
redirect_to '/device/update/' + params[:dp][:device_id]
end

Resources