Array not saving user input in ruby - ruby-on-rails

This is what I have so far, but the array is not saving the first value if the user enters 2 or more car types. If I remove the car.get_ methods the program runs fine without saving the users input. Is there a method I am missing?
class Cars
def set_make(make)
end
def set_model(model)
end
def set_year(year)
end
array_of_cars = Array.new
print "How many cars do you want to create? "
num_cars = gets.to_i
puts
for i in 1.. num_cars
puts
print "Enter make for car #{i}: "
make = gets.chomp
print "Enter model for car #{i}: "
model = gets.chomp
print "Enter year of car #{i}: "
year = gets.to_i
c = Car.new
c.set_make(make)
c.set_model(model)
c.set_year(year)
array_of_cars << c
end
puts
puts "You have the following cars: "
for car in array_of_cars
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
end

Ok so the primary issue is that you calling the Car.new where the Car class is defined. You should not have an array of cars in the car class. You could try creating a Dealership class that has an array of cars then you could do something like this
class Dealership
attr_accessor :car_lot
def initialize
#car_lot = []
end
def add_car(car)
#car_lot << car
end
end
crazy_carls = Dealership.new
car1 = Car.new(make, model, year)
crazy_carls.add_car(car1)
crazy_carls.car_lot.each do |car
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
You need to refactor the car class a good deal first though, look into how to use the initialize method, attr_accessor, and instance variables.

Related

I want to concatenate two values into a single string

I have two different values systolic and diastolic blood pressure readings in string. When those two values come from front-end I'll store them into a single string, e.g., if systolic ='120' and diastolic='80' I want bp='120/80'
module Api
module V1
module CheckinMachine
class BpsController < ApplicationController
include MachineError
before_action :authenticate_user!
def create
raise BatteryNotFunctionalError if battery_functional?
# user = User.find_by!(bp_machine_imei: params[:imei])
health_reading = current.health_readings.create!(key: :blood_pressure, value: bp_value)
Solera::PostActivityApi.call(user,
bp,
health_reading.solera_activities.new)
head :ok
rescue ActiveRecord::RecordNotFound => _e
render_machine_error and return
end
def show
puts params
end
private
def bp
{
systolic_blood_pressure: params[:systolic],
diastolic_blood_pressure: params[:diastolic]
}
end
end
end
end
end
That's what i have tried, what do i do to make it exactly like i want it to be
like bp = '120/80'
Since you already have the 2 values stored in params, this is super easy:
bp = " #{params[:systolic] / #{params[:diastolic]} "
> bp = " 120/80 "
Remember that Ruby has the variable substitution in strings using the #{x} syntax where x is a variable value.
So for instance:
x = "apples"
y = 5
string = "I have #{y} units of #{x} to sell you"
puts(string)
> "I have 5 units of apples to sell you"

How to create an instance of a class in Rails, giving each new instance 5 has_many through relationships

I want to make an instance of my Test class get five practice questions through a join class when it is initialised. If a test is an "exam" then it should just get 5 exam questions without a join class. (the question types have different models)
So far It doesn't behave the way I expect
self.practice_questions = []
it makes 5 join classes every time, but the array of self.practice_questions stays empty.
def get_questions
puts "ASDASDASDASDSAD"
array = []
if self.for_practice
puts "ASDASDASOASKODKSAOKDASODKOASKDSAOKDOASKDOASK"
PracticeQuestion.sort_for_selection[0...5].each do |question|
array << question
question.use_practice_question
end
elsif for_practice === false
puts self.exam_questions
if self.exam_questions.length ===0
grab 5 unused exam type questions
ExamQuestion.unused[0...5].each do |question|
puts "grabbing question #{question.title}"
question.test = self
question.use_question
end
end
puts "hello"
puts self.practice_questions.length
self.practice_questions ||= array
self.save
puts self.practice_questions.length
self.practice_questions.each {|question| puts question.title}
end
self.practice_questions ||= array will only assign the array if self.practice_questions is false or nil, are you sure it's one of those?
If practice_questions is a has_many, try one of this:
array.each do |el|
self.practice_questions << el
end
or:
self.practice_questions_ids = array.map(&:id)
https://guides.rubyonrails.org/association_basics.html#has-many-association-reference

Ruby loops and classes; splitting a string into an array and back to a string again

Ruby newbie here working on loops with classes. I was supposed create a method that would take a string and add exclamation points to the end of each word (by making it an array with .split) and join the 'exclaimed' words as a string again. I've been at this for two hours already and decided I should seek help. I have a handful of ideas but I keep coming up with a NoMethod error. Below is one of ways that made sense to me but of course, it doesn't work. I've also added specs at the very end.
class StringModifier
attr_accessor :string
def initialize(string)
#string = string
end
def proclaim
new_array = []
string.split.each do |word|
new array = "#{word}!"
new_array.join
end
new_array
end
end
SPECS
describe StringModifier do
describe "#proclaim" do
it "adds an exclamation mark after each word" do
blitzkrieg_bop = StringModifier.new("Hey ho let's go").proclaim
expect(blitzkrieg_bop).to eq("Hey! ho! let's! go!")
end
end
end
Write your method as:
def proclaim
string.split.map { |word| "#{word}!" }.join(" ")
end
Or write it as :
def proclaim
a = string.split
("%s! " * a.size % a).strip
end
Tested :
[30] pry(main)> a = "Hey ho let's go".split
=> ["Hey", "ho", "let's", "go"]
[31] pry(main)> ("%s! " * a.size % a).strip
=> "Hey! ho! let's! go!"
[32] pry(main)>

Rotten Tomatoes API with Ruby

I'm new to Ruby & trying out this API. I want to build a simple game which asks an user for two movies names to guess / compare which one received a better audience rating or any other comparative parameter. The API is working and I tried substituting the code with the user input but that's where it breaks down. (I have also mentioned the class I am calling)
require_relative 'workspace/lib/select'
require_relative 'workspace/lib/brand'
require 'json'
require 'rest-client'
# puts "hello world"
def create_reviewer
puts "What is your name?"
name = gets.strip
puts "So, #{name} what genre are you interested in?"
genre = gets.strip
Select.new(name, genre)
end
def create_brand
puts "Enter the first brand"
brand_a = gets.strip
puts "Enter the second brand"
brand_b = gets.strip
Brand.new(brand_a, brand_b)
end
review = create_reviewer
brands = create_brand
def get_rotten_tomatoes
response = JSON.load(RestClient.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=SECRET&q=#{brand_a}&page_limit=30'))
response["movies"].map do |entry|
brand_a = entry["ratings"]["audience_score"]
brand_b = entry["ratings"]["critics_score"]
final_score = {brand_a: audience_score, brand_b: critics_score}
final_score
end
goodies = get_rotten_tomatoes
puts goodies
----
class Brand
attr_accessor :brand_a, :brand_b
def initialize(name, genre)
#brand_a = brand_a
#brand_b = brand_b
end
# def to_s
# "Tenant: #{#name} \n Credit Score: #{#credit_score}."
# end
end

Array of objects in ruby

I am trying to learn ruby and have a doubt regarding passing arrays of objects as function parameters and printing it in the function.
I have an array that contains an array of objects as follows
describe Name
par1 = "John"
par2 = "Miley"
par3 = "Maria"
#obj_arr = [Name.new(par1),Name.new(par2),Name.new(par3)]
Name.func1(#obj_arr)
I want to print the name "John", "Miley" and "Maria" in the function and I wrote the function func1 is as follows :
def self.func1(parameter)
parameter.each do |p|
puts p
end
end
This did not print the names. Am I going wrong in accessing the obj_arr in the function?
I think your problem might be the to_s method of the object. You should override it to print what you want. BTW, the syntax in your question is a bit off. I think the definition of the function should be def self.func1 and that your missing an end.
This is the code I tested:
irb(main):001:0> class Name
irb(main):002:1> def self.func1(parameter)
irb(main):003:2> parameter.each do |p|
irb(main):004:3* puts p
irb(main):005:3> end
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> class Name
irb(main):009:1> def initialize(name)
irb(main):010:2> #name = name
irb(main):011:2> end
irb(main):012:1> end
=> nil
irb(main):013:0> Name.func1([Name.new('a'), Name.new('b')])
#<Name:0x2163dc8>
#<Name:0x2163d98>
=> [#<Name:0x2163dc8 #name="a">, #<Name:0x2163d98 #name="b">]
irb(main):014:0> class Name
irb(main):015:1> def to_s
irb(main):016:2> #name
irb(main):017:2> end
irb(main):018:1> end
=> nil
irb(main):019:0> Name.func1([Name.new('a'), Name.new('b')])
a
b
=> [a, b]
irb(main):020:0>
It may be that func1 is defined on a instance of class Name and not the class itself?
Try:
class Name
def self.func1(parameter)
parameter.each do |p|
puts p
end
end
end

Resources