Iterating over loops in ruby? - ruby
I am new to ruby. I am trying to create a letter counter. my intended output was supposed to be [2,"I"] but I keep getting [3,"D]. Any help in understanding where I went wrong would be so helpful, thank you.
class LetterCounter
def initialize(text)
#text = text
end
def calculate_most_common()
counter = Hash.new(1)
most_common = nil
most_common_count = 1
#text.chars.each do |char|
next unless is_letter?(char)
counter[char] = (counter[char] || 1) + 1
if counter[char] > most_common_count
most_common = char
most_common_count += counter[char]
end
end
return [most_common_count, most_common]
end
private
def is_letter?(letter)
return letter =~ /[a-z]/i
end
end
counter = LetterCounter.new("Digital Punk")
p counter.calculate_most_common
# Intended output:
# [2, "i"]
Try:
class LetterCounter
def initialize(text)
#text = text
end
def calculate_most_common()
arr=#text.scan(/[a-z]/i)
arr.each_with_object(Hash.new(0)) { |n,h| h[n] += 1 }.max_by(&:last)
end
end
counter = LetterCounter.new("Digital Punk")
p counter.calculate_most_common
Prints:
["i", 2]
If you want to fix yours, try:
class LetterCounter
def initialize(text)
#text = text
end
def calculate_most_common()
counter = Hash.new(0)
most_common = nil
most_common_count = 0
#text.chars.each do |char|
next unless is_letter?(char)
counter[char] += 1
if counter[char]>most_common_count
most_common=char
most_common_count=counter[char]
end
end
return [most_common_count, most_common]
end
private
def is_letter?(letter)
return letter =~ /[a-z]/i
end
end
counter = LetterCounter.new("Digital Punk")
p counter.calculate_most_common
class LetterCounter
def initialize(text)
#text = text
end
def calculate_most_common()
counter = Hash.new(0) # wrong initialization in your code
most_common = nil
most_common_count = 0
#text.chars.each do |char|
next unless is_letter?(char)
counter[char] = (counter[char] || 1) + 1
puts "#{char} #{counter[char]}"
if counter[char] > most_common_count
puts "most common: #{most_common_count} #{char} #{counter[char]}"
most_common = char
most_common_count = counter[char] # error in your code
end
end
return [most_common_count, most_common]
end
private
def is_letter?(letter)
return letter =~ /[a-z]/i
end
end
counter = LetterCounter.new("Digital Punk")
p counter.calculate_most_common
The initial counters are at 1. These should be 0 since you are incrementing inside your loop anyways.
On the First Iteration -
Hash counter[char] is being initialized to 1 ( From Hash.new(1) ),
Then counter[char] is increased to 1 on first loop and the most_common_count is also increased by 1.
Which leads to D having value 3.
since most_common_count is already at 3 - the loop would no longer go into the if condition - as other characters would reach only 2 ( 1 from Hash.new and 1 from counter[char] +1 )
The if condition is > most_common_count and not >= - hence even if i reaches 3 - condition would not execute.
Hence the output [3, 'D']
Try this instead :
class LetterCounter
def initialize(text)
#text = text
end
def calculate_most_common()
counter = Hash.new(0)
most_common = nil
most_common_count = 0
#text.chars.each do |char|
next unless is_letter?(char)
puts char + " ==> " + counter[char].to_s # To know the value on each iteration
counter[char] += 1
if counter[char] > most_common_count
most_common = char
most_common_count = counter[char]
puts [most_common_count, most_common] # To know when the if condition is executed
end
end
return [most_common_count, most_common]
end
private
def is_letter?(letter)
return letter =~ /[a-z]/i
end
end
counter = LetterCounter.new("Digital Punk")
p counter.calculate_most_common
Related
How do I fix a problem to call a function in Ruby?
I'm trying to use some ruby code that I've found in Github. I've downloaded the code and did the necessary imports the "requires" and tried to run it as it is described in the readme file on github repository. The code is the following: In the file pcset_test.rb the code is the following: require './pcset.rb' require 'test/unit' # # When possible, test cases are adapted from # Introduction to Post-Tonal Theory by Joseph N. Straus, # unless obvious or otherwise noted. # class PCSetTest < Test::Unit::TestCase def test_init #assert_raise(ArgumentError) {PCSet.new []} assert_raise(ArgumentError) {PCSet.new [1, 2, 3, 'string']} assert_raise(ArgumentError) {PCSet.new "string"} assert_raise(ArgumentError) {PCSet.new [1, 2, 3.6, 4]} assert_equal([0, 1, 2, 9], PCSet.new([0, 1, 2, 33, 13]).pitches) assert_equal([3, 2, 1, 11, 10, 0], PCSet.new_from_string('321bac').pitches) assert_equal([0,2,4,5,7,11,9], PCSet.new([12,2,4,5,7,11,9]).pitches) assert_nothing_raised() {PCSet.new []} end def test_inversion end def test_transposition end def test_multiplication end # # set normal prime forte # # 0,2,4,7,8,11 7,8,11,0,2,4 0,1,4,5,7,9 6-31 # 0,1,2,4,5,7,11 11,0,1,2,4,5,7 0,1,2,3,5,6,8 7-Z36 # 0,1,3,5,6,7,9,10,11 5,6,7,9,10,11,0,1,3 0,1,2,3,4,6,7,8,10 9-8 # def test_normal_form testPC = PCSet.new [0,4,8,9,11] assert_kind_of(PCSet, testPC.normal_form) assert_equal([8,9,11,0,4], testPC.normal_form.pitches) assert_equal([10,1,4,6], PCSet.new([1,6,4,10]).normal_form.pitches) assert_equal([2,4,8,10], PCSet.new([10,8,4,2]).normal_form.pitches) assert_equal([7,8,11,0,2,4], PCSet.new([0,2,4,7,8,11]).normal_form.pitches) assert_equal([11,0,1,2,4,5,7], PCSet.new([0,1,2,4,5,7,11]).normal_form.pitches) assert_equal([5,6,7,9,10,11,0,1,3], PCSet.new([0,1,3,5,6,7,9,10,11]).normal_form.pitches) end def test_prime_form assert_equal([0,1,2,6], PCSet.new([5,6,1,7]).prime.pitches) assert_equal([0,1,4], PCSet.new([2,5,6]).prime.pitches) assert_equal([0,1,4,5,7,9], PCSet.new([0,2,4,7,8,11]).prime.pitches) assert_equal([0,1,2,3,5,6,8], PCSet.new([0,1,2,4,5,7,11]).prime.pitches) assert_equal([0,1,2,3,4,6,7,8,10], PCSet.new([0,1,3,5,6,7,9,10,11]).prime.pitches) end def test_set_class testPcs = PCSet.new([2,5,6]) testPrime = testPcs.prime assert_equal([ [2,5,6], [3,6,7], [4,7,8], [5,8,9], [6,9,10], [7,10,11], [8,11,0],[9,0,1], [10,1,2],[11,2,3],[0,3,4], [1,4,5], [6,7,10],[7,8,11],[8,9,0], [9,10,1],[10,11,2],[11,0,3], [0,1,4], [1,2,5], [2,3,6], [3,4,7], [4,5,8], [5,6,9] ].sort, PCSet.new([2,5,6]).set_class.map{|x| x.pitches}) assert_equal(testPcs.set_class.map{|x| x.pitches}, testPrime.set_class.map{|x| x.pitches}) end def test_interval_vector assert_equal([2,1,2,1,0,0], PCSet.new([0,1,3,4]).interval_vector) assert_equal([2,5,4,3,6,1], PCSet.new([0,1,3,5,6,8,10]).interval_vector) assert_equal([0,6,0,6,0,3], PCSet.new([0,2,4,6,8,10]).interval_vector) end def test_complement assert_equal([6,7,8,9,10,11], PCSet.new([0,1,2,3,4,5]).complement.pitches) assert_equal([3,4,5], PCSet.new([0,1,2], 6).complement.pitches) end # # Test values from (Morris 1991), pages 105-111 # Citation: # Morris. Class Notes for Atonal Music Theory # Lebanon, NH. Frog Peak Music, 1991. # def test_invariance_vector assert_equal([1,0,0,0,5,6,5,5],PCSet.new([0,2,5]).invariance_vector) assert_equal([2,2,2,2,6,6,6,6],PCSet.new([0,1,6,7]).invariance_vector) assert_equal([6,6,6,6,6,6,6,6],PCSet.new([0,2,4,6,8,10]).invariance_vector) assert_equal([1,0,0,0,0,0,0,0],PCSet.new([0,1,2,3,4,5,8]).invariance_vector) assert_equal([1,0,0,1,0,0,0,0],PCSet.new([0,1,2,3,5,6,8]).invariance_vector) assert_equal([12,12,12,12,0,0,0,0],PCSet.new([0,1,2,3,4,5,6,7,8,9,10,11]).invariance_vector) end # # Test values from (Huron 1994). Huron rounds, thus the 0.01 margin of error. # Citation: # Huron. Interval-Class Content in Equally Tempered Pitch-Class Sets: # Common Scales Exhibit Optimum Tonal Consonance. # Music Perception (1994) vol. 11 (3) pp. 289-305 # def test_huron h1 = PCSet.new([0,1,2,3,4,5,6,7,8,9,10,11]).huron assert_in_delta(-0.2, h1[0], 0.01) assert_in_delta(0.21, h1[1], 0.01) h2 = PCSet.new([0,2,4,5,7,9,11]).huron assert_in_delta(4.76, h2[0], 0.01) assert_in_delta(0.62, h2[1], 0.01) end def test_coherence end end And in the file pcset.rb the folloing code: # # => PCSet Class for Ruby # => Beau Sievers # => Hanover, Fall 2008. # # # TODO: Make this a module to avoid namespace collisions. # Lilypond and MusicXML output # include Math def choose(n, k) return [[]] if n.nil? || n.empty? && k == 0 return [] if n.nil? || n.empty? && k > 0 return [[]] if n.size > 0 && k == 0 c2 = n.clone c2.pop new_element = n.clone.pop choose(c2, k) + append_all(choose(c2, k-1), new_element) end def append_all(lists, element) lists.map { |l| l << element } end def array_to_binary(array) array.inject(0) {|sum, n| sum + 2**n} end # the following method is horrifically inelegant # but avoids monkey-patching. # TODO: do this right, incl. error checking def pearsons(x, y) if !x.is_a?(Array) || !y.is_a?(Array) then raise StandardError, "x and y must be arrays", caller end if x.size != y.size then raise StandardError, "x and y must be same size", caller end sum_x = x.inject(0) {|sum, n| sum + n} sum_y = y.inject(0) {|sum, n| sum + n} sum_square_x = x.inject(0) {|sum, n| sum + n * n} sum_square_y = y.inject(0) {|sum, n| sum + n * n} xy = [] x.zip(y) {|a, b| xy.push(a * b)} sum_xy = xy.inject(0) {|sum, n| sum + n} num = sum_xy - ((sum_x * sum_y)/x.size) den = Math.sqrt((sum_square_x - ((sum_x*sum_x)/x.size)) * (sum_square_y - ((sum_y*sum_y)/x.size))) (num/den) end class PCSet include Comparable attr_reader :pitches, :base, :input def initialize(pcarray, base = 12) if pcarray.instance_of?(Array) && pcarray.all?{|pc| pc.instance_of?(Fixnum)} #base, #input = base, pcarray #pitches = pcarray.map{ |x| x % #base }.uniq else raise ArgumentError, "Improperly formatted PC array", caller end end def PCSet.new_from_string(pcstring, base = 12) if base > 36 then raise StandardError, "Use PCSet.new to create pcsets with a base larger than 36", caller end pcarray = [] pcstring.downcase.split(//).each do |c| if c <= 'z' and c >= '0' then pcarray.push(c.to_i(36)) end end PCSet.new pcarray, base end def <=>(pcs) #pitches <=> pcs.pitches end def [](index) #pitches[index] end # Intersection def &(other) PCSet.new #pitches & other.pitches end # Union def |(other) PCSet.new #pitches | other.pitches end def inspect #pitches.inspect end def length #pitches.length end def invert(axis = 0) PCSet.new #pitches.map {|x| (axis-x) % #base} end def invert!(axis = 0) #pitches.map! {|x| (axis-x) % #base} end def transpose(interval) PCSet.new #pitches.map {|x| (x + interval) % #base} end def transpose!(interval) #pitches.map! {|x| (x + interval) % #base} end def multiply(m = 5) PCSet.new #pitches.map {|x| (x * m) % #base} end def multiply!(m = 5) #pitches.map! {|x| (x * m) % #base} end def zero transpose(-1 * #pitches[0]) end def zero! transpose!(-1 * #pitches[0]) end def transpositions (0..(#base-1)).to_a.map{|x| #pitches.map {|y| (y + x) % #base}}.sort.map {|x| PCSet.new x} end def transpositions_and_inversions(axis = 0) transpositions + invert(axis).transpositions end # # Normal form after Straus. Morris and AthenaCL do this differently. # def normal_form tempar = #pitches.sort arar = [] # [[1,4,7,8,10],[4,7,8,10,1], etc.] get each cyclic variation tempar.each {arar.push PCSet.new(tempar.unshift(tempar.pop))} most_left_compact(arar) end def normal_form! #pitches = normal_form.pitches end def is_normal_form? self.pitches == self.normal_form.pitches end def set_class transpositions_and_inversions.map{|pcs| pcs.normal_form}.sort end def prime most_left_compact([normal_form.zero, invert.normal_form.zero]) end def prime! self.pitches = self.prime.pitches end def is_prime? self.pitches == self.prime.pitches end def complement new_pitches = [] #base.times do |p| if !#pitches.include? p then new_pitches.push p end end PCSet.new new_pitches end def full_interval_vector pairs = choose(#pitches, 2) # choose every pc pair intervals = pairs.map {|x| (x[1] - x[0]) % #base} # calculate every interval i_vector = Array.new(#base-1).fill(0) intervals.each {|x| i_vector[x-1] += 1} # count the intervals i_vector end def interval_vector i_vector = full_interval_vector (0..((#base-1)/2)-1).each {|x| i_vector[x] += i_vector.pop} i_vector end # # Morris's invariance vector # def invariance_vector(m = 5) t = transpositions.map!{|pcs| self & pcs} ti = invert.transpositions.map!{|pcs| self & pcs} tm = multiply(m).transpositions.map!{|pcs| self & pcs} tmi = invert.multiply(m).transpositions.map!{|pcs| self & pcs} tc = complement.transpositions.map!{|pcs| self & pcs} tic = complement.invert.transpositions.map!{|pcs| self & pcs} tmc = complement.multiply(m).transpositions.map!{|pcs| self & pcs} tmic = complement.invert.multiply(m).transpositions.map!{|pcs| self & pcs} [t, ti, tm, tmi, tc, tic, tmc, tmic].map{|x| x.reject{|pcs| pcs.pitches != #pitches}.length} end # Huron's aggregate dyadic consonance measure. # Huron. Interval-Class Content in Equally Tempered Pitch-Class Sets: # Common Scales Exhibit Optimum Tonal Consonance. # Music Perception (1994) vol. 11 (3) pp. 289-305 def huron if #base != 12 then raise StandardError, "PCSet.huron only makes sense for mod 12 pcsets", caller end # m2/M7 M2/m7 m3/M6 M3/m6 P4/P5 A4/d5 huron_table = [-1.428, -0.582, 0.594, 0.386, 1.240, -0.453] interval_consonance = [] interval_vector.zip(huron_table) {|x, y| interval_consonance.push(x * y) } aggregate_dyadic_consonance = interval_consonance.inject {|sum, n| sum + n} [aggregate_dyadic_consonance, pearsons(interval_vector, huron_table)] end # # Balzano's vector of relations. Citation for all Balzano methods: # # Balzano. "The Pitch Set as a Level of Description for Studying Musical # Pitch Perception" in Music, Mind, and Brain ed. Clynes. Plenum Press. 1982. # def vector_of_relations (0..length-1).to_a.map do |i| (0..length-1).to_a.map do |j| (#pitches[(i + j) % length] - #pitches[i]) % #base end end end # # Checks if the set satisfies Balzano's uniqueness. # def is_unique? vector_of_relations.uniq.size == vector_of_relations.size end # # Checks if the set satisfies Balzano's scalestep-semitone coherence. # For all s[i] and s[i1]: # j < k => v[i][j] < v[i1][k] # Where j and k are scalestep-counting indices. # And unless v[i][j] == 6 (a tritone), in which case the strict inequality is relaxed. # def is_coherent? v = vector_of_relations truth_array = [] all_pair_indices = choose((0..length-1).to_a, 2) all_pair_indices.each do |i, i1| all_pair_indices.each do |j, k| if v[i][j] == 6 truth_array.push(v[i][j] <= v[i1][k]) else truth_array.push(v[i][j] < v[i1][k]) end if v[i1][j] == 6 truth_array.push(v[i1][j] <= v[i][k]) else truth_array.push(v[i1][j] < v[i][k]) end end end !truth_array.include?(false) end # # Strict Balzano coherence, no inequality relaxation for tritones. # def is_strictly_coherent? v = vector_of_relations truth_array = [] all_pair_indices = choose((0..length-1).to_a, 2) all_pair_indices.each do |i, i1| all_pair_indices.each do |j, k| truth_array.push(v[i][j] < v[i1][k]) truth_array.push(v[i1][j] < v[i][k]) end end !truth_array.include?(false) end def notes(middle_c = 0) noteArray = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'] if #base != 12 then raise StandardError, "PCSet.notes only makes sense for mod 12 pcsets", caller end out_string = String.new transpose(-middle_c).pitches.each do |p| out_string += noteArray[p] + ", " end out_string.chop.chop end def info print "modulo: #{#base}\n" print "raw input: #{#input.inspect}\n" print "pitch set: #{#pitches.inspect}\n" print "notes: #{notes}\n" print "normal: #{normal_form.inspect}\n" print "prime: #{prime.inspect}\n" print "interval vector: #{interval_vector.inspect}\n" print "invariance vector: #{invariance_vector.inspect}\n" print "huron ADC: #{huron[0]} pearsons: #{huron[1]}\n" print "balzano coherence: " if is_strictly_coherent? print "strictly coherent\n" elsif is_coherent? print "coherent\n" else print "false\n" end end # def lilypond # # end # # def musicXML # # end ############################################################################### private # # Convert every pitch array to a binary representation, e.g.: # [0,2,4,8,10] -> 010100010101 # 2^n: BA9876543210 # The smallest binary number is the most left-compact. # def most_left_compact(pcset_array) if !pcset_array.all? {|pcs| pcs.length == pcset_array[0].length} raise ArgumentError, "PCSet.most_left_compact: All PCSets must be of same cardinality", caller end zeroed_pitch_arrays = pcset_array.map {|pcs| pcs.zero.pitches} binaries = zeroed_pitch_arrays.map {|array| array_to_binary(array)} winners = [] binaries.each_with_index do |num, i| if num == binaries.min then winners.push(pcset_array[i]) end end winners.sort[0] end end I'm calling them as follows: > my_pcset = PCSet.new([0,2,4,6,8,10]) > my_pcset2 = PCSet.new([1,5,9]) It shoud return: > my_pcset = PCSet.new([0,2,4,6,8,10]) => [0, 2, 4, 6, 8, 10] > my_pcset2 = PCSet.new([1,5,9]) => [1, 5, 9] But is returning nothing. The code is available on github Thanks
Try this in terminal: irb -r ./path_to_directory/pcset.rb and then initialize the objects.
I think the documentation for the repo is bad as it does not explain how you should be running this. The result of my_pcset = PCSet.new([0,2,4,6,8,10]) should set my_pcset to an instance of a PCSet not an array, so these lines from the README file are confusing at best. 3. How to use it Make new PCSets: my_pcset = PCSet.new([0,2,4,6,8,10]) => [0, 2, 4, 6, 8, 10] my_pcset2 = PCSet.new([1,5,9]) => [1, 5, 9] Looking at the code, I see inspect has been delegated to #pitches def inspect #pitches.inspect end I think if you inspect my_pcset you will get the expected result. my_pcset = PCSet.new([0,2,4,6,8,10]) p my_pcset # will print [0, 2, 4, 6, 8, 10] or `my_pcset.inspect` will return what you are expecting.
FizzBuzz Program Output in form of table
I have written the logic for the program to perform FizzBuzz operations: fizzbuzz module FizzBuzz class Operation def input puts 'Enter a number upto which Fizz/Buzz needs to be printed' num = gets.chomp.to_i fizzbuzz_function(num) end def fizzbuzz_function(num) for i in 1..num if i % 3 == 0 && i % 5 == 0 puts 'FizzBuzz' elsif i % 3 == 0 puts 'Fizz' elsif i % 5 == 0 puts 'Buzz' else puts i end end end end res = Operation.new res.input end But I am trying to print the output in form of a table.
Here is FizzBuzz in form of a table: def fizzbuzz_gen(num) Enumerator.new do |y| (1..num).each do |i| if i % 3 == 0 && i % 5 == 0 y << 'FizzBuzz' elsif i % 3 == 0 y << 'Fizz' elsif i % 5 == 0 y << 'Buzz' else y << i.to_s end end end end def fill_to_width(width, e) result = "" future_length = -1 while result.length + future_length < width result << e.next result << " " future_length = e.peek.length end result.center(width) end def format_table(num) fb = fizzbuzz_gen(num) begin puts fill_to_width(75, fb) puts fill_to_width(75, fb) loop do puts "%10s%s%31s%s" % ["", fill_to_width(12, fb), "", fill_to_width(12, fb)] end rescue StopIteration end end format_table(100) There may be less numbers output than specified, in order for one leg not to be shorter than another.
What's wrong with my code?
def encrypt(string) alphabet = ("a".."b").to_a result = "" idx = 0 while idx < string.length character = string[idx] if character == " " result += " " else n = alphabet.index(character) n_plus = (n + 1) % alphabet.length result += alphabet[n_plus] end idx += 1 end return result end puts encrypt("abc") puts encrypt("xyz") I'm trying to get "abc" to print out "bcd" and "xyz" to print "yza". I want to advance the letter forward by 1. Can someone point me to the right direction?
All I had to do was change your alphabet array to go from a to z, not a to b, and it works fine. def encrypt(string) alphabet = ("a".."z").to_a result = "" idx = 0 while idx < string.length character = string[idx] if character == " " result += " " else n = alphabet.index(character) n_plus = (n + 1) % alphabet.length result += alphabet[n_plus] end idx += 1 end return result end puts encrypt("abc") puts encrypt("xyz")
Another way to solve the issue, that I think is simpler, personally, is to use String#tr: ALPHA = ('a'..'z').to_a.join #=> "abcdefghijklmnopqrstuvwxyz" BMQIB = ('a'..'z').to_a.rotate(1).join #=> "bcdefghijklmnopqrstuvwxyza" def encrypt(str) str.tr(ALPHA,BMQIB) end def decrypt(str) str.tr(BMQIB,ALPHA) end encrypt('pizza') #=> "qjaab" decrypt('qjaab') #=> "pizza"
Alternatively if you don't want to take up that memory storing the alphabet you could use character codings and then just use arithmetic operations on them to shift the letters: def encrypt(string) result = "" idx = 0 while idx < string.length result += (string[idx].ord == 32 ? (string[idx].chr) : (string[idx].ord+1).chr) idx += 1 end result end Other strange thing about ruby is that you do not need to explicitly return something at the end of the method body. It just returns the last thing by default. This is considered good style amongst ruby folks.
Your question has been answered, so here are a couple of more Ruby-like ways of doing that. Use String#gsub with a hash CODE_MAP = ('a'..'z').each_with_object({}) { |c,h| h[c] = c < 'z' ? c.next : 'a' } #=> {"a"=>"b", "b"=>"c",..., "y"=>"z", "z"=>"a"} DECODE_MAP = CODE_MAP.invert #=> {"b"=>"a", "c"=>"b",..., "z"=>"y", "a"=>"z"} def encrypt(word) word.gsub(/./, CODE_MAP) end def decrypt(word) word.gsub(/./, DECODE_MAP) end encrypt('pizza') #=> "qjaab" decrypt('qjaab') #=> "pizza" Use String#gsub with Array#rotate LETTERS = ('a'..'z').to_a #=> ["a", "b", ..., "z"] def encrypt(word) word.gsub(/./) { |c| LETTERS.rotate[LETTERS.index(c)] } end def decrypt(word) word.gsub(/./) { |c| LETTERS.rotate(-1)[LETTERS.index(c)] } end encrypt('pizza') #=> "qjaab" decrypt('qjaab') #=> "pizza"
Inconsistencies in using <% break if %> statements causing never ending loops *Fixed
I have written two functions where in one of the the break if array.length == num statements works, while the other does not. Here are the methods and their tests, starting with the working: def primes(n) ret = [] return [] if n < 1 for num in 2..+1.0/0.0 ret << num if prime?(num) break if ret.count == n end ret end def prime?(num) (1..num).select {|x| num % x == 0}.count == 2 end puts "\nPrimes:\n" + "*" * 15 + "\n" puts primes(0) == [] puts primes(1) == [2] puts primes(2) == [2,3] puts primes(6) == [2,3,5,7,11,13]
Sum of positive elements in linked list
I need to make program, but i can't finish it and get into mess with methods. The aim is to find the sum of all positive of elements and add it in the end. I am just started teach classes and methods. How can I make the sum of all positive elements in my final array? Here is my code: class Node attr_accessor :value, :next_node def initialize val,next_in_line #value = val #next_nodex = next_in_line puts "Initialized a Node with value: " + value.to_s end end class LinkedList def initialize val #head = Node.new(val,nil) end def add(value) current = #head while current.next_node != nil current = current.next_node end current.next_node = Node.new(value,nil) self end def delete(val) current = #head if current.value == val #head = #head.next_node else current = #head while (current != nil) && (current.next_node != nil) && ((current.next_node).value != val) current = current.next_node end if (current != nil) && (current.next_node != nil) current.next_node = (current.next_node).next_node end end end def display current = #head full_list = [] while current.next_node != nil full_list += [current.value.to_s] current = current.next_node end full_list += [current.value.to_s] puts full_list.join(" ") end def sum end end puts "\n" list = [*-99..99].shuffle ll = LinkedList.new(list[0]) (1..9).each do |i| ll.add(list[i]) end puts "\nDo you want item to add? '1' - yes '0' - no" adding = gets.to_i puts "\n" if adding == 1 ll.add(list[10]) end puts "\nDisplaying Linked List:" ll.display puts "\nDo you want to delete item? '1' - yes '0' - no" deleting = gets.to_i if deleting == 1 puts "Type in and delete item and then display the linked list:" deleteInt = gets.to_i ll.delete(deleteInt) end puts ll.display puts "\nThe sum of all positive elements" ll.sum
Firstly, You have mistype in Node.initialize method - #next_nodex should be #next_node i think. Secondly, don't use puts 2 times: puts ll.display at the end. To add in array preferably use << symbol. Another thing, i can't see any concept difference between display and sum methods, except one condition. According to this, it should be like: def sum current = #head sum = 0 while current.next_node != nil sum += current.value if current.value > 0 current = current.next_node end sum += current.value if current.value > 0 sum end or with dry: def full_list current = #head full_list = [] while current.next_node != nil full_list << current.value current = current.next_node end full_list << current.value full_list end def display puts full_list.join(' ') end def sum full_list.keep_if { |x| x > 0 }.reduce(:+) end All code