Quickly create 3 ruby objects - ruby-on-rails

I am trying to create 3 objects in a loop like this...
3.times do |i|
#part + i.to_s = Part.create(part_number: "000#{i + 1}")
end
I get the error
NoMethodError: undefined method to_s=' for 0:Fixnum`
I think its obvious what I am trying to do? I'd like three parts (#part1/#part2/#part3) with part numbers 0001/2/3 after the loop runs.

As Roman already suggested, you should use an array.
However, to answer you question:
3.times do |i|
instance_variable_set("#part#{i + 1}", Part.create(part_number: "000#{i + 1}"))
end
Or even:
(1..3).each do |i|
instance_variable_set("#part#{i}", Part.create(part_number: "000#{i}"))
end

Related

Rails views output is different than Puma web server logs

I have a ruby script called abc.rb in rails config/initializers
require 'http'
class Abc
def initialize(url)
#url = url
#doc = web_lookup(#url)
end
def web_lookup(url_to_open)
begin
return Nokogiri::HTML(HTTP.get(url_to_open).to_s)
rescue
"Please check your URL!"
end
end
def frequency_count
#word_array = #doc.css("p").text.split(" ")
#occurance = Hash.new(0)
#word_array.each {|x| #occurance[x.downcase] += 1 }
#occurance.each {|x,y|
if y > 5
puts "#{x} : #{y} times"
end
}
end
end
And I'm trying to access that script's class in a rails controller.
class UrlsController < ApplicationController
def index
#url_to_check = Abc.new("http://ecodehut.com/linux")
end
end
Everything is fine so far but when I call this variable in index.html.erb <%= #url_to_check.frequency_count %> output is this:
{"it’s"=>1, "like"=>1, "asking"=>1, "“should"=>1, "i"=>5, "go"=>3, "to"=>14, "school?”"=>1, "and"=>8, "“would"=>1, "get"=>1, "a"=>3, "job"=>1, "if"=>2, "school?”.list"=>1, "of"=>1, "advantages"=>1, "is"=>5, "never"=>1, "ending"=>1, "elaborating"=>1, "each"=>1, "throw"=>1, "your"=>2, "mouse"=>1, "away"=>1, "this"=>3, "time."=>1, "keyboard"=>1, "all"=>1, "need"=>1, "mozart."=>1, "navigate..."=>1, "before"=>2, "we"=>1, "begin"=>1, "with"=>3, "configuration"=>1, "here"=>1, "download"=>1, "install"=>2, "system."=>1, "after"=>1, "come"=>1, "back"=>1, "continue."=>1}
But my expected output is this:
to : 14 times
and : 8 times
you : 9 times
the : 6 times
I'm not getting why rails printing everything inside the hash instead of the key values with values bigger than 5 like mentioned in the frequency_count method.
P.S: Abc.rb script results fine and dandy when ran in terminal using ruby Abc.rb
Plese change this and try again
def frequency_count
#word_array = #doc.css("p").text.split(" ")
#occurance = Hash.new(0)
#word_array.each {|x| #occurance[x.downcase] += 1 }
#occurance.select {|x, y| y> 5}
end
The reason is the last line of your method is
#occurance.each {|x,y|
if y > 5
puts "#{x} : #{y} times"
end
}
Just iterate all key and values inside #occurance variable but not sort based on the count. So you are getting all key values in the views instead which has count more than 5.
When you do #occurance.select {|x, y| y> 5}, which filter your hash and gives you the desired values which count is more than 5. Now you can just loop it and print inside views.
Hope you understand.
Update
In your index.html.erb put this code, where you would like to print hash details
<% #occurance.each do |key, value| %>
<span><%= "#{key}: #{value}" %></span><br />
<% end %>

Adding User Input to a hash? Ruby

I am trying to create some simple programs as trying to learn Ruby and then move on to rails, I am just playing about to try and get used to the flow of how different types of code work variables, loops etc.
I am trying to create a simple book system were I already have 3 books in my hash and then I want to list the books already in the library in the console and then I want to be able to add new books and then also loop through and display the new list to the console.
require 'rubygems'
class GetDetailsFromUser
books = {
Eagle_Eye: 1,
Eage_Eye1: 2,
Eagle_Eye2: 3
}
books.each do |i|
puts i
end
while true
add = gets.chomp
break if add.empty?
books << add
end
puts 'New list is below'
books.each do |i|
puts i
end
end
Were am I going wrong? I manage to print out the hash to the console, however, I get an error message
undefined method '<<' for {:Eagle_Eye=>1,...
Why is the method undefined? books << add? This should add a new book to the book hash table?
Add your second number with it. Here is a working example I wrote for you
Live Demo - VISIT THIS LINK
books = {
Eagle_Eye: 1,
Eage_Eye1: 2,
Eagle_Eye2: 3
}
books.each do |i|
puts i
end
while true
puts "What book would you like to add?"
add = gets.chomp
if add.empty? == true
puts "Error - You did not enter a title for a book"
break
else
books.max_by do |book,id|
#list_number = id
end
books[add.to_sym]=#list_number
break
end
end
puts 'New list is below'
books.each do |i|
puts i
end
refactored version of #ExecutiveCloser
books = {
Eagle_Eye: 1,
Eage_Eye1: 2,
Eagle_Eye2: 3
}
books.each do |i|
puts i
end
add = ""
while add.empty? do
puts "What book would you like to add?"
add = gets.chomp
books[add.to_sym] = books.size + 1 unless add.empty?
end
puts 'New list is below'
books.each do |i|
puts i
end
https://repl.it/CDK2/3
Ruby has a documentation site. E. g. Hash documentation clearly states, that there is no method << defined on the hash instance.
<< method is defined on Array.
Why would you expect “books << add should add a new book to the book hash table”?
There is another glitch within your code: you execute everything on class definition level, which makes absolutely no sense in this case.
Since it is unclear what do you want to achieve, I am unable to provide a ready-to-go-with solution.

rails method from multiple methods

So I have this code in my Rails presenter(similar to Draper gem):
def title
h.link_to 'Favor', favor_path(#favor) + asked_or_published? + user_link
end
def asked_or_published?
if asked_favor?
h.content_tag(:p, "published by")
elsif published_favor?
h.content_tag(:p, "asked by")
end
end
def user_link
h.link_to #favor.favor_asker.firstname, h.user_path(#favor.favor_asker)
end
And I'm calling the title method in my view. The problem is that calling this method only returns the link_to 'Favor' part and not the rest. Why is that?
Thanks in advance!
It's a grouping priority issue, the + asked_or_published? + user_link bits are being added to the path generated by favor_path(#favor). Not sure if they're also being escaped correctly, but that is not relevant.
Replace this:
h.link_to 'Favor', favor_path(#favor) + asked_or_published? + user_link
with:
h.link_to('Favor', favor_path(#favor)) + asked_or_published? + user_link

How to compare arrays based on the value contained on a certain index in Ruby?

I have two arrays, one with strings that are questions and the other one with it's answers which are also strings, the answer for the question which is in the first position of the array #questions is also in the first position but in the #answers, and it's the same for all the questions, so what i want to do is to ask the question to the user, and if he doesn't answer what was expected, he asked to try again.
This is my code so far:
but i'm getting the following error : file_mng.rb:72:in block in play': undefined method[]' for nil:NilClass (NoMethodError)
def play
arrange_arrays
#The method arrange_arrays fills the arrays #questions and #answers in
#a way that, the answer for the question in the first position of the
#array #questions is located also in the first position of the array #answers,
#so the index matches for the arrays.
puts
#questions.each_with_index do |question, i|
puts question
puts
puts "TYPE YOUR ANSWER"
puts
answer = gets.chomp
while answer != #answers[i]
puts
puts "INCORRECT, TRY AGAIN"
end
puts
puts "CORRECT !"
end
puts
puts "QUESTIONS ARE OVER, CONGRATULATIONS!"
end
def arrange_arrays
#everything located in a odd line is an question
#everything lcoated in an even line is an answer
File.open("questionary.out").each_line do |line|
i = i+1
if i % 2 == 0
#answers << line.to_s.downcase.chomp
else
#questions << line.to_s.downcase.chomp
end
end
end
Thanks a million for reading this.
The error is on this line:
while answer != #answers[i]
As the error message suggests, you're calling [] on nil, which means #answers is nil. You should look at your arrange_arrays method, as it doesn't seem to be setting #answers.
P.S. There's another problem on this line: You're using while where you should be using if. Once you fix the #answers problem, this will print "INCORRECT, TRY AGAIN" infinitely when the answer is incorrect.

ordering in rails based on the count of a word present in a single column

I have a model named Vendor. I have three different models associated with it.
Testimonial
Service
Works
I have to look up each of the tables and list the vendors(limit 5) which have the word "example" most number of times in a column in one of these models. How do I do this in rails?
I have something like this
Vendor.joins(:testimonials).where("testimonials.content LIKE ?","%example%")
I need to find the vendors who has the maximum number of occurrences of the word "example"
I hope I got you right now:
a=[]
vendors.each do |v|
c=0
c=v.testimonial.scan(/example/).count
if c>0
a=a.concat([{vendor: v, counts: c}])
end
In Ruby you can count the occurrence of a substring in a string in this way, for example
s = "this is a string with an example, example, example"
s.scan(/example/).count # => 3
This is how I ended up doing this. Not sure if my question was asked correctly. I made this with the help of a previous answer by #user3383458
vendor = Hash.new
Vendor.all.each do |v|
testi_word_count = 0
service_word_count = 0
title_word_count = 0
v.testimonials.each do |testi|
testi_word_count += testi.content.scan(/#{word_to_search}/).count
Rails.logger.info "testi_word_count"
Rails.logger.info testi_word_count
end
v.services.each do |service|
service_word_count += service.name.scan(/#{word_to_search}/).count
Rails.logger.info "service_word_count"
Rails.logger.info service_word_count
end
v.works.each do |work|
title_word_count += work.title.scan(/#{word_to_search}/).count
Rails.logger.info "title_word_count"
Rails.logger.info title_word_count
end
vendor[v]=testi_word_count + service_word_count + title_word_count
end

Resources