Im trying to add objects to an array by using push. I have a program where u can register guests. When I choose the checkin option from my menu Im unable to add the new guest to the guest history.
This dont work:
def self.check_in
puts "Welcome to the checkin"
puts "Please state your first name: "
firstName = gets.chomp
puts "Please state your last name:"
lastName = gets.chomp
puts "Write your address: "
address = gets.chomp
puts "and your phone number: "
phone = gets.chomp
puts "finally, your arrival date!"
arrived = gets.chomp
newPLot = $camping.generateParkingLot
guest = Guest.new(firstName, lastName, address, phone, arrived)
$camping.current_guests[newPLot-1] = guest
puts "The registration was a success!! You have received plot " + newPLot.to_s + "."
#all_guests.push(guest) # adds the guest to the history
end
Here I get a check_in': undefined methodpush' for nil:NilClass (NoMethodError). But if I comment out this line:
##all_guests.push(guest) # adds the guest to the history
Im able to register a guest. An then when I choose the 3 option from my menu which is:
def self.do_action(action)
# utför händelse baserat på valet
case action
when 1:
check_in
when 2:
check_out
when 3:
puts $camping.current_guests
when 4:
puts $camping.all_guests
when 5:
puts "You are now leaving the camping, welcome back!"
exit
end
end
Then I see the guest there. The only problem is that I cant do the 4 option which is to show all guests because I have commented out that line of code. So to round things up how can I use this line of code:
#all_guests.push(guest) # adds the guest to the history
Without receiving the error message?? Thankful for all help!
#all_guests isn't defined in the file where you get the error, it's defined in the $camping global. Change the code to
$camping.all_guests.push(...)
and see if that works better for you.
Related
This project is a simple Ruby project, Github Repo, which I am trying to re-build using TDD, and I'm using Ruby (ruby 2.7.3) and rspec (RSpec 3.10).
My issue is, no matter how I try to simulate user input (see the commented out lines of my 'Test Code below to see what I've tried.)
Am I missing something? I feel like I don't understand this well enough, I've tried most of the suggestions I can find on Google.
Code file: /lib/address_checker.rb
Test file: /spec/address_checker_spec.rb
I am testing the AddressChecker class, specifically the following functions:
def handle_manual_input
puts "Add at least 2 Addresses, hit enter after each address, type 'quit' when done"
while true do
address = gets.chomp
break if address == "quit"
check_ethereum_address_validity(address) ? #origin_addresses << address : (puts "Error: Invalid Ethereum Address")
end
end
def input_origin_addresses_manually?(y_n)
if y_n == "y"
handle_manual_input
elsif y_n == "n"
#origin_addresses = ["0x72140C1886f8F2Dd932DCe06795901F8FB6378a7","0x0613Cd2076bd432C7A60a1b926b11B17BaAaFE11"]
else
print "Please only enter 'y' or 'n' into 'input_origin_addresses_manually'"
end
end
I'm trying to test whether the output of input_origin_addresses_manually?("y") will populate #origin_addresses with more than 1 address.
When I run rspec though, I am prompted for user input (because of my address = gets.chomp within handle_manual_input.
Terminal Output from rspec:
➜ cryptoAddressWeb git:(main) ✗ rspec
...Add at least 2 Addresses, hit enter after each address, type 'quit' when done
and my desired input would loop like this:
...Add at least 2 Addresses, hit enter after each address, type 'quit' when done
0xa95aea385130718be87b380b419eeac8da40de55
0xa95aea385130718be87b380b419eeac8da40de55
quit
....
Test Code
it 'If user wants to add their own addresses, check that they add more than 1 address' do
subject.input_origin_addresses_manually?("y")
# let(:user_input) { ["rock\n", "rock\n"] }
# allow_any_instance_of(Object).to receive(:gets).and_return('0xa95aea385130718be87b380b419eeac8da40de55', '0xa95aea385130718be87b380b419eeac8da40de55', 'quit')
# expect(subject).to receive(:puts).with("Add at least 2 Addresses, hit enter after each address, type 'quit' when done")
# allow(subject).to receive(:gets).and_return('0xa95aea385130718be87b380b419eeac8da40de55', '0xa95aea385130718be87b380b419eeac8da40de55', 'quit')
# subject.stub(gets: 'user input')
# expect(STDOUT).to receive(:puts).with("Add at least 2 Addresses, hit enter after each address, type 'quit' when done")
# allow(STDIN).to receive(:gets).and_return('0xa95aea385130718be87b380b419eeac8da40de55', '0xa95aea385130718be87b380b419eeac8da40de55', 'quit')
# expect($stdout).to receive(:puts).with("Add at least 2 Addresses, hit enter after each address, type 'quit' when done")
# allow($stdin).to receive(:gets).and_return('0xa95aea385130718be87b380b419eeac8da40de55', '0xa95aea385130718be87b380b419eeac8da40de55', 'quit')
expect(subject.origin_addresses.length).to be > 1
end
Would really appreciate assistance!
Thank you,
Ed
[How to] Simulate Multiple Gets (User Input) on rspec
class Inquisitor
def gets_twice
[gets, gets]
end
end
RSpec.describe Inquisitor do
describe '#gets_twice' do
it 'calls gets twice' do
inq = Inquisitor.new
allow(inq).to receive(:gets).and_return('Apricot', 'Banana')
expect(inq.gets_twice).to eq(%w[Apricot Banana])
end
end
end
I have some troubles with my code using Ruby. its just for a terminal program, so no website or anything.
In my code I Will have the user create a login. Then I will have the user to login, but I cant seem to figure out how to check if password or username is correct.
The program should compare whatever the user types in as a username/password with the file (userdatabase) - I think i got that right.
Now I am trying to stop the user if the input is not found in the user database, using a while loop, but i cant seem to make that work.
Code:
puts "What will be your user name?"
username = gets.chomp
puts "What will be your password?"
password = gets.chomp
puts "Please repeat your password."
passwordsafe = gets.chomp
f = File.new("student.txt", "w+")
f.puts username + ";" + password + ";" + passwordsafe
f.close
puts "well done, you have created a new user."
lines = IO.readlines("student.txt")
lines.each{|line| print(line)}
puts "now you need to login."
puts "What is your username?"
username = gets.chomp
File.open("student.txt") do |f|
f.any? do |line|
while line.include?(username)
end
end
elsif puts "Sorry your username was incorrect"
end
#lines = IO.readlines("student.txt")
#lines.each{|line| (line)}
puts "what is your password?"
password = gets.chomp
The while is unnecessary.
The username check currently like this:
File.open("student.txt") do |f|
f.any? do |line|
while line.include?(username)
end
end
Could be like this:
File.open("student.txt").each_line.any? do |line|
line.include?(username)
end
Or collapsed to a single line like this:
File.open("student.txt").each_line.any?{ |l| l.include?(username) }
Check the docs on the any? method to make sure you understand what it's expecting: http://ruby-doc.org/core-2.4.2/Enumerable.html#method-i-any-3F
As for the rest of the syntax errors, I'll leave those up to you ;)
i am new to programming in ruby, and i am trying to get the value of json['earning_rate_hr'] but i get an error, in '[]': no implicit conversion of String into Integer (TypeError)
i know and i understand the error, however this is not my main question here is my file :
checkingchecker.rb :
#require_relative '../lib/hackex/net/typhoeus'
require_relative '../lib/hackex'
require 'rubygems'
require 'json'
file = 'accounts1.txt'
f = File.open file, 'r'
puts "MADE BY THE PEOPLE, FOR THE PEOPLE #madebylorax"
puts ""
puts "--------------------------------------------------------"
puts ""
while line = f.gets
line = line.chomp.split(';')
email, password = line
puts "logging in as " + email
HackEx.LoginDo(email, password) do |http, auth_token, user|
puts "getting info..."
user = HackEx::Request.Do(http, HackEx::Request.UserInfo(auth_token))['user']
puts "receieved user info!"
bank = HackEx::Request.Do(http, HackEx::Request.UserBank(auth_token))['user_bank']
puts "recieved bank info!"
json = HackEx::Request.Do(http, HackEx::Request.UserSpam(auth_token))['spam']
puts "recieved spam info!"
puts json['earning_rate_hr'] #error line, the error is because this is an array, and it cant be turned into integer, i was wondering if there is a way to use puts on it without trying to make it an integer
userchecking = bank["checking"]
checking = userchecking.scan(/.{1,3}/).join(',')
puts email + " has in Checking: BTC #{checking}"
puts ""
puts "--------------------------------------------------------"
puts ""
end
end
i tried to do puts json, it puts items like this one :
{"id"=>"9867351", "user_id"=>"289108", "victim_user_id"=>"1512021",
"victim_ip"=
"86.60.226.175", "spam_level"=>"50", "earning_rate_hr"=>"24300", "total_earning s"=>"13267800", "started_at"=>"2015-11-01 07:46:59",
"last_collected_at"=>"2015- 11-24 01:46:59"}
what i want to do is select the earning_rate_hr for each one of them and add them together, however i do not have a clue on how to do that, since the error is not fixed and i cant get the value of it
ps : i tried turning it into a Hash, and i also tried using .first, but .first only shows the firs one, i want to show all of them, thank you
I know you from line messenger, I haven't used ruby codes in a long time and this one keeps giving me cloudflare errors, I'm not sure if its because of server downtime/maintainance or whatever but yeah anyway heres your script, enjoy farming ;) -LineOne
PS, I changed a few strings to make it look a lil cleaner so you can see the spam income easier, and added the sleep (1) because sleeping for one second before reconnecting helps to prevent cloudflare errors
also you don't need to require json or rubygems in your hackex scripts because its required in the library so its all covered pre-user-input/script
require_relative 'libv5/lib/hackex'
while 1<2
begin
print'Filename: '
fn=gets.chomp
file = fn+'.txt'
f = File.open file, 'r'
puts "MADE BY THE PEOPLE, FOR THE PEOPLE #madebylorax" #helped by lineone
puts ""
puts "--------------------------------------------------------"
puts ""
while line = f.gets
line = line.chomp.split(';')
email, password = line
HackEx.LoginDo(email, password) do |http, auth_token, user|
puts "Retrieving Info..."
puts''
user = HackEx::Request.Do(http, HackEx::Request.UserInfo(auth_token))['user']
bank = HackEx::Request.Do(http, HackEx::Request.UserBank(auth_token))['user_bank']
json = HackEx::Request.Do(http, HackEx::Request.UserSpam(auth_token))['spam']
cash_count=0
tot_count=0
json.each do |j|
earn_rate = j['earning_rate_hr']
total= j['total_earnings']
cash_count+=earn_rate.to_i
tot_count+=total.to_i
end
print "#{email}: current earnings: #{cash_count} per hour, Total earnings #{tot_count},"
userchecking = bank["checking"]
checking = userchecking.scan(/.{1,3}/).join(',')
puts " #{checking} BTC in Checking"
puts ""
puts "--------------------------------------------------------"
puts ""
sleep 1
end
end
rescue
puts"#{$!}"
end
end
Thats fine you can also calculate the total income of your farms by adding new variables at the top example a=0 then adding the number at the end a+=tot_count
This should help:
earning_rates = json.map{|e| e["earning_rate_hr"]}
puts "Earning rates per hour: #{earning_rates.join(" ")}"
puts "Sum of earning rates: #{earning_rates.map{|e| e.to_i}.inject{|sum, x| sum + x}}"
I'm making a basic "Helper" program..
Anyway here's the code:
def sayHelp()
puts "------------List of help and commands-------------"
puts "Help-- Shows a list of commands."
puts "Start [PROGRAM] (PROGRAM ARGS)-- Starts the specified program."
return true
end
version = "1.0"
ccommand = ""
puts "Welcome to RubyBot " + version + "."
puts "------------------------------------"
sleep(3)
system "clear" or system "cls"
puts "Enter \"help\" for a list of commands."
puts "Please enter a command: "
ccommand = gets
if ccommand == "help"
sayHelp()
else
puts "Not right bro"
end
I go ahead and run this and enter help but it just chucks Not right bro up at me.. What am I doing wrong?
ccommand = gets
The string returned by gets has a trailing new line character, remove it and it will work:
ccommand = gets.chomp
Im trying to practice pulling APIs with Ruby. Im trying to pull videogame news from Steam.
Below is my code.
The idea is, when the program is ran, the the user is prompted to enter a game ID between 200 and 440.
Anything not in between dont exist or the numbers arent continuous.
Anyway, Im trying to pass the gameID variable into the string:
"http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=#{gameID}&count=5&maxlength=300&format=json"
The string is wrapped in a function. When I try to run the program, the error says wrong number of arguments ( 0 for 1 ).
What am i doing wrong, and what am I missing? Many thanks in advance as usual :)
*been doing nothing but asking questions so far, hope to contribute someday once I get better :)
require 'json'
require 'HTTParty'
puts "----------------------------------------------------------"
puts "Welcome to my practice"
puts "The purpose of this exercise is to use the SteamAPI"
puts "to pull videogame news from Steam"
puts "----------------------------------------------------------"
reset = true
while reset
puts "Please enter a game ID between 200 - 440"
gameID = gets.to_i
if gameID < 200
puts "--Invalid input--"
reset = true
elsif gameID > 400
puts "--Invalid input--"
reset= true
else
reset = false
end
end
puts "--------------------Loading API----------------------------"
def get_news( gameID )
string = "http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=#{gameID}&count=5&maxlength=300&format=json"
page = HTTParty.get( string )
browse = page["appnews"]["newsitems"]
browse.map do |content|
{title: content["title"], contents: content["contents"]}
end
end
def display_story( content )
puts "Title: #{content[:title]}"
puts "--------------------"
puts " #{content[:contents]}"
puts "--------------------"
end
get_news.each do |content|
display_story( content )
end
You've defined get_news to take a gameID argument, but you haven't passed it anything. At the end of your file, you need get_news(gameID).each.