Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Ruby Fibonacci Multiplication Table This was an interview question.
Recently jumped into software development, and came across this challenge. Can you show me below, how can I write the Fibonacci multiplication table in Ruby language? For the last couple of days, I was trying to implement it but seems like I am facing a brick wall and the code makes me feel insane and also I failed on the interview, but that does not matter at the moment. I will appreciate any kind of help. Thanks a lot.
ApplicationController:
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
end
get '/' do
#time_of_day = Time.now
erb :index
end
end
FibonacciController:
class FibonacciController < ApplicationController
get '/fibonacci' do
place = params[:place].to_i
#sequence = fib(place)
erb :fibonacci
end
def fib(place)
res = []
a = 0
b = 1
while b < place do
res << b
a,b = b,a+b
end
res
end
end
Fibonacci.erb
<div class="container">
<h1> Fibonacci sequence: </h1>
<div class="sub-container">
<p> Generated fibonacci sequence: </p>
<%= #sequence.join(', ') %>
</div>
</div>
Index.erb
<div class="container">
Date and time: <%= #time_of_day %>
<br>
<h1> Fibonacci Multiplication Table </h1>
<p> Enter your number below: </p>
<form method="GET" action="/fibonacci">
<label for="sequence">
<input type="integer" name="place" placeholder="Insert your number">
<input type="submit">
</form>
</div>
(This is the ultimate goal of this challenge)
FibonacciController code
class FibonacciController < ApplicationController
get '/fibonacci' do
place = params[:place].to_i
sequence = fib(place)
#table = generate_table(sequence)
erb :fibonacci
end
def fib(place)
return [] if place <= 0
a = 0
b = 1
res = [a]
while res.length < place do
res << b
a,b = b, a+b
end
res
end
def generate_table(sequence)
return [] if sequence.length.zero?
cols = []
(sequence.length + 1).times do |row|
row_data = []
(sequence.length + 1).times do |col|
row_data << generate_table_element(row, col, sequence)
end
cols << row_data
end
cols
end
def generate_table_element(row, col, sequence)
return '_' if row.zero? && col.zero?
return sequence[col - 1] if row.zero?
return sequence[row - 1] if col.zero?
sequence[col - 1] * sequence[row - 1]
end
end
And in erb file
<p> Generated fibonacci sequence: </p>
<% #table.each do |table_row| %>
<%= table_row.join(',') %>
<br/>
<% end %>
Related
I'm making a list of categories but I need the header to only show the first letter without repeating
This is for a list of all the categories of a store
Controller:
def show
#category = Category.friendly.find(params[:id])
#category_articles = #category.articles.paginate(page: params[:page], per_page: 12)
end
view:
<div class="container" id="tag-container">
<% #categories.each do |category| %>
<section>
<h2><%= category.name.first %></h2>
<%= link_to "#{category.name}", category_path(category)%>
<span>(<%= pluralize(category.articles.count,"")%>)</span>
</section>
<% end %>
</div>
I'll really appreciate if you can help me with this.
Supposing categories to be sorted by name, this can be an option. I'm using plain Ruby, but you can do the same with Rails. Consider categories array as the collection of records.
categories = %W(bat bet bot cat cut dot git got gut)
grouped_categories = categories.group_by { |w| w[0] }
Grouping by first letter ({ |w| w[0] }) using Enumerable#group_by. The method returns a Hash that you can iterate with nested loop:
grouped_categories
#=> {"b"=>["bat", "bet", "bot"], "c"=>["cat", "cut"], "d"=>["dot"], "g"=>["git", "got", "gut"]}
grouped_categories.each do |initial, vals|
puts "-#{initial}"
vals.each do |val|
puts "----#{val}"
end
end
It prints:
-b
----bat
----bet
----bot
-c
----cat
----cut
-d
----dot
-g
----git
----got
----gut
If you wish the categories alphabetised,
categories = ["gut", "git", "bot", "cut", "got", "cat", "dot", "bet", "bat"]
categories.sort.chunk { |w| w[0] }.each { |ltr,a| puts "#{ltr}: #{a.join(' ')}" }
b: bat bet bot
c: cat cut
d: dot
g: git got gut
I have a function in my .erb file and in it I have the following:
<%select id ="dropdown">
<option disabled selected value="select"> - select - </option>
<% #variable.each do |x| %>
<%= "<option value='#{x['code']}'>#{x['description']} </option>".html_safe %>
<% end %>
<%/select>
But I need to have two items (TUA and CRL) to be displayed at the top and the rest to be displayed in alpha order (which currently is) so it should be .
<%select id ="dropdown">
<option disabled selected value="select"> - select - </option>
<% #variable.each do |x| %>
<% next if x['code'] == 'TUA' or x['code'] == 'CRL' %>
<%= "<option value='#{x['code']}'>#{x['description']} </option>".html_safe %>
<% end %>
<%/select>
How can I do that ? I have hardcoded it and I don't want that.
Not sure how #variable is declared, but what if you try arranging it in the controller?
#variable = []
#variable << Variable.find_by(code: 'TUA')
#variable << Variable.find_by(code: 'CRL')
#variables = Variable.all.order('code DESC')
#variables.each do |x|
if x.code != 'TUA' && x.code!= 'CRL'
#variable << x
end
end
Trying to show the #total variable but it always says 0.
What's the correct way to get it to display on the page?
Currently i am doing...
main.rb
require 'sinatra'
get '/' do
#array = [1, 7, 3, 0]
#index = params[:index].to_i
#total = 1
def get_products_of_all_ints_except_at_index()
#array.delete_at(#index)
#array.each do |i|
#total *= i
end
end
get_products_of_all_ints_except_at_index()
erb :home
end
home.erb
<form action="/">
<input type="number" name="index" placeholder="index">
<button>Calculate</button>
</form>
<%= #total %>
In your #array, the last element is 0. Because you are iterating over it and multiplying the total with each element, total is 0 too.
This question already has an answer here:
Rails in rendering unnecessary information
(1 answer)
Closed 8 years ago.
I have a function in ruby
def words
ret =""
res = Net::HTTP.start(url.host, url.port) {|http|http.request(req)}
res.body.each_line do |line|
words = line.split("\"")
ret << words[1] << " "
end
return ret
end
say ret returns "Bill Dan Mike Sarah".
in my view I am doing
<%= #class.words.split(" ").each do |name| %>
<p><%= name %></p>
<% end %>
Instead of just displaying each name on a line, it does
Bill
Dan
Mike
Sarah
["Bill", "Dan", "Mike", "Sarah"] #this shouldn't be printed
What is causing it to display the entire array there at the end? How do I prevent this?
Remove an extra = from first line in each:
<% #class.words.split(" ").each do |name| %>
<p><%= name %></p>
<% end %>
Here's an example HTML fragment:
<p class="stanza">Thus grew the tale of Wonderland:<br/>
Thus slowly, one by one,<br/>
Its quaint events were hammered out -<br/>
And now the tale is done,<br/>
And home we steer, a merry crew,<br/>
Beneath the setting sun.<br/></p>
I need to surround each word with a <span id="w0">Thus </span> like this:
<span id='w1'>Anon,</span> <span id='w2'>to</span> <span id='w3'>sudden</span>
<span id='w4'>silence</span> <span id='w5'>won,</span> ....
I written this which creates the new fragment. How do I replace/swap the new for old?
def callchildren(n)
n.children.each do |n| # call recursively until arrive at a node w/o children
callchildren(n)
end
if n.node_type == 3 && n.to_s.strip.empty? != true
new_node = ""
n.to_s.split.each { |w|
new_node = new_node + "<span id='w#{$word_number}'>#{w}</span> "
$word_number += 1
}
# puts new_node
# HELP? How do I get new_node swapped in?
end
end
My attempt to provide a solution for your problem:
require 'nokogiri'
Inf = 1.0/0.0
def number_words(node, counter = nil)
# define infinite counter (Ruby >= 1.8.7)
counter ||= (1..Inf).each
doc = node.document
unless node.is_a?(Nokogiri::XML::Text)
# recurse for children and collect all the returned
# nodes into an array
children = node.children.inject([]) { |acc, child|
acc += number_words(child, counter)
}
# replace the node's children
node.children = Nokogiri::XML::NodeSet.new(doc, children)
return [node]
end
# for text nodes, we generate a list of span nodes
# and return it (this is more secure than OP's original
# approach that is vulnerable to HTML injection)n
node.to_s.strip.split.inject([]) { |acc, word|
span = Nokogiri::XML::Node.new("span", node)
span.content = word
span["id"] = "w#{counter.next}"
# add a space if we are not at the beginning
acc << Nokogiri::XML::Text.new(" ", doc) unless acc.empty?
# add our new span to the collection
acc << span
}
end
# demo
if __FILE__ == $0
h = <<-HTML
<p class="stanza">Thus grew the tale of Wonderland:<br/>
Thus slowly, one by one,<br/>
Its quaint events were hammered out -<br/>
And now the tale is done,<br/>
And home we steer, a merry crew,<br/>
Beneath the setting sun.<br/></p>
HTML
doc = Nokogiri::HTML.parse(h)
number_words(doc)
p doc.to_xml
end
Given a Nokogiri::HTML::Document in doc, you could do something like this:
i = 0
doc.search('//p[#class="stanza"]/text()').each do |n|
spans = n.content.scan(/\S+/).map do |s|
"<span id=\"w#{i += 1}\">" + s + '</span>'
end
n.replace(spans.join(' '))
end