Ruby: calculate the frequencies of the string text letters





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I was creating a ruby programme that will calculate the frequency of each letter appearing in my text and will be return it as a Hash.



Below is my code:



class LetterHistogram
attr_reader :letters
attr_accessor :text

def initialize(t = "Hello World!")
@text = t
end

def display
calculateFrequencies
("A".."Z").each {|x| puts "#{x}: " + "*" * letters[x]}
end

private
attr_writer :letters

def calculateFrequencies
calcuFreq = String.new(text)
calcuFreq.upcase!.gsub!(/W+/, '')
letters.clear
letters.default = 0
calcuFreq.each_char {|char| letters[char] += 1}
end
end


But I getting this error when I run the display method
enter image description here



What is the error means and how to solve it?










share|improve this question


















  • 5





    Please include your error message as part of the question in text, not as an image...if that image gets taken down or otherwise goes away, this question becomes unanswerable.

    – Simple Lime
    Nov 17 '18 at 0:57


















0















I was creating a ruby programme that will calculate the frequency of each letter appearing in my text and will be return it as a Hash.



Below is my code:



class LetterHistogram
attr_reader :letters
attr_accessor :text

def initialize(t = "Hello World!")
@text = t
end

def display
calculateFrequencies
("A".."Z").each {|x| puts "#{x}: " + "*" * letters[x]}
end

private
attr_writer :letters

def calculateFrequencies
calcuFreq = String.new(text)
calcuFreq.upcase!.gsub!(/W+/, '')
letters.clear
letters.default = 0
calcuFreq.each_char {|char| letters[char] += 1}
end
end


But I getting this error when I run the display method
enter image description here



What is the error means and how to solve it?










share|improve this question


















  • 5





    Please include your error message as part of the question in text, not as an image...if that image gets taken down or otherwise goes away, this question becomes unanswerable.

    – Simple Lime
    Nov 17 '18 at 0:57














0












0








0








I was creating a ruby programme that will calculate the frequency of each letter appearing in my text and will be return it as a Hash.



Below is my code:



class LetterHistogram
attr_reader :letters
attr_accessor :text

def initialize(t = "Hello World!")
@text = t
end

def display
calculateFrequencies
("A".."Z").each {|x| puts "#{x}: " + "*" * letters[x]}
end

private
attr_writer :letters

def calculateFrequencies
calcuFreq = String.new(text)
calcuFreq.upcase!.gsub!(/W+/, '')
letters.clear
letters.default = 0
calcuFreq.each_char {|char| letters[char] += 1}
end
end


But I getting this error when I run the display method
enter image description here



What is the error means and how to solve it?










share|improve this question














I was creating a ruby programme that will calculate the frequency of each letter appearing in my text and will be return it as a Hash.



Below is my code:



class LetterHistogram
attr_reader :letters
attr_accessor :text

def initialize(t = "Hello World!")
@text = t
end

def display
calculateFrequencies
("A".."Z").each {|x| puts "#{x}: " + "*" * letters[x]}
end

private
attr_writer :letters

def calculateFrequencies
calcuFreq = String.new(text)
calcuFreq.upcase!.gsub!(/W+/, '')
letters.clear
letters.default = 0
calcuFreq.each_char {|char| letters[char] += 1}
end
end


But I getting this error when I run the display method
enter image description here



What is the error means and how to solve it?







ruby frequency






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 17 '18 at 0:51









RickyPangRickyPang

137




137








  • 5





    Please include your error message as part of the question in text, not as an image...if that image gets taken down or otherwise goes away, this question becomes unanswerable.

    – Simple Lime
    Nov 17 '18 at 0:57














  • 5





    Please include your error message as part of the question in text, not as an image...if that image gets taken down or otherwise goes away, this question becomes unanswerable.

    – Simple Lime
    Nov 17 '18 at 0:57








5




5





Please include your error message as part of the question in text, not as an image...if that image gets taken down or otherwise goes away, this question becomes unanswerable.

– Simple Lime
Nov 17 '18 at 0:57





Please include your error message as part of the question in text, not as an image...if that image gets taken down or otherwise goes away, this question becomes unanswerable.

– Simple Lime
Nov 17 '18 at 0:57












1 Answer
1






active

oldest

votes


















0














The main problem is that in calculateFrequencies you are using a not assigned variable: letters. So, when you call calculateFrequencies in display, letters = nil and calling .clear on nil returns the error.



This is a modified version of the code, using snake_case (which is the Ruby writing standard).



class LetterHistogram
attr_accessor :text

def initialize(t = "Hello World!")
@text = t
end

def display
calculate_frequencies.each { |letter, freq| puts "#{letter}: #{freq}"}
end

private

def calculate_frequencies
freq = @text.upcase.gsub!(/W+/, '').each_char.with_object(Hash.new(0)) { |letter, freq| freq[letter] += 1 }
freq.sort_by{ |letter, freq| freq }.reverse # just to sort
end
end


Instantiating an object and calling .display on it:



senctence = LetterHistogram.new
senctence.display

#=> L: 3
#=> O: 2
#=> D: 1
#=> R: 1
#=> W: 1
#=> E: 1
#=> H: 1


How it works



For calculating the frequency I used a Hash populated by: https://ruby-doc.org/core-2.5.1/Enumerable.html#method-i-each_with_object



Printing out freq from calculate_frequencies you can see it:



#=> {"H"=>1, "E"=>1, "L"=>3, "O"=>2, "W"=>1, "R"=>1, "D"=>1}





Alternatively, if you want also not used letters, you can initialise the freq hash with all values to 0, then update the hash, something like this:

freq = ("A".."Z").each_with_object({}) { |letter, freq| freq[letter] = 0 }
"Hello World!".upcase.gsub!(/W+/, '').each_char { |letter| freq[letter] += 1 }

#=> {"A"=>0, "B"=>0, "C"=>0, "D"=>1, "E"=>1, "F"=>0, "G"=>0, "H"=>1, "I"=>0, "J"=>0, "K"=>0, "L"=>3, "M"=>0, "N"=>0, "O"=>2, "P"=>0, "Q"=>0, "R"=>1, "S"=>0, "T"=>0, "U"=>0, "V"=>0, "W"=>1, "X"=>0, "Y"=>0, "Z"=>0}




Finally, to print out the istogram:



freq.each { |letter, freq| puts "#{letter}: " + "◼︎" * freq if freq > 0 }

#=> D: ◼︎
#=> E: ◼︎
#=> H: ◼︎
#=> L: ◼︎◼︎◼︎
#=> O: ◼︎◼︎
#=> R: ◼︎
#=> W: ◼︎





share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347190%2fruby-calculate-the-frequencies-of-the-string-text-letters%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The main problem is that in calculateFrequencies you are using a not assigned variable: letters. So, when you call calculateFrequencies in display, letters = nil and calling .clear on nil returns the error.



    This is a modified version of the code, using snake_case (which is the Ruby writing standard).



    class LetterHistogram
    attr_accessor :text

    def initialize(t = "Hello World!")
    @text = t
    end

    def display
    calculate_frequencies.each { |letter, freq| puts "#{letter}: #{freq}"}
    end

    private

    def calculate_frequencies
    freq = @text.upcase.gsub!(/W+/, '').each_char.with_object(Hash.new(0)) { |letter, freq| freq[letter] += 1 }
    freq.sort_by{ |letter, freq| freq }.reverse # just to sort
    end
    end


    Instantiating an object and calling .display on it:



    senctence = LetterHistogram.new
    senctence.display

    #=> L: 3
    #=> O: 2
    #=> D: 1
    #=> R: 1
    #=> W: 1
    #=> E: 1
    #=> H: 1


    How it works



    For calculating the frequency I used a Hash populated by: https://ruby-doc.org/core-2.5.1/Enumerable.html#method-i-each_with_object



    Printing out freq from calculate_frequencies you can see it:



    #=> {"H"=>1, "E"=>1, "L"=>3, "O"=>2, "W"=>1, "R"=>1, "D"=>1}





    Alternatively, if you want also not used letters, you can initialise the freq hash with all values to 0, then update the hash, something like this:

    freq = ("A".."Z").each_with_object({}) { |letter, freq| freq[letter] = 0 }
    "Hello World!".upcase.gsub!(/W+/, '').each_char { |letter| freq[letter] += 1 }

    #=> {"A"=>0, "B"=>0, "C"=>0, "D"=>1, "E"=>1, "F"=>0, "G"=>0, "H"=>1, "I"=>0, "J"=>0, "K"=>0, "L"=>3, "M"=>0, "N"=>0, "O"=>2, "P"=>0, "Q"=>0, "R"=>1, "S"=>0, "T"=>0, "U"=>0, "V"=>0, "W"=>1, "X"=>0, "Y"=>0, "Z"=>0}




    Finally, to print out the istogram:



    freq.each { |letter, freq| puts "#{letter}: " + "◼︎" * freq if freq > 0 }

    #=> D: ◼︎
    #=> E: ◼︎
    #=> H: ◼︎
    #=> L: ◼︎◼︎◼︎
    #=> O: ◼︎◼︎
    #=> R: ◼︎
    #=> W: ◼︎





    share|improve this answer






























      0














      The main problem is that in calculateFrequencies you are using a not assigned variable: letters. So, when you call calculateFrequencies in display, letters = nil and calling .clear on nil returns the error.



      This is a modified version of the code, using snake_case (which is the Ruby writing standard).



      class LetterHistogram
      attr_accessor :text

      def initialize(t = "Hello World!")
      @text = t
      end

      def display
      calculate_frequencies.each { |letter, freq| puts "#{letter}: #{freq}"}
      end

      private

      def calculate_frequencies
      freq = @text.upcase.gsub!(/W+/, '').each_char.with_object(Hash.new(0)) { |letter, freq| freq[letter] += 1 }
      freq.sort_by{ |letter, freq| freq }.reverse # just to sort
      end
      end


      Instantiating an object and calling .display on it:



      senctence = LetterHistogram.new
      senctence.display

      #=> L: 3
      #=> O: 2
      #=> D: 1
      #=> R: 1
      #=> W: 1
      #=> E: 1
      #=> H: 1


      How it works



      For calculating the frequency I used a Hash populated by: https://ruby-doc.org/core-2.5.1/Enumerable.html#method-i-each_with_object



      Printing out freq from calculate_frequencies you can see it:



      #=> {"H"=>1, "E"=>1, "L"=>3, "O"=>2, "W"=>1, "R"=>1, "D"=>1}





      Alternatively, if you want also not used letters, you can initialise the freq hash with all values to 0, then update the hash, something like this:

      freq = ("A".."Z").each_with_object({}) { |letter, freq| freq[letter] = 0 }
      "Hello World!".upcase.gsub!(/W+/, '').each_char { |letter| freq[letter] += 1 }

      #=> {"A"=>0, "B"=>0, "C"=>0, "D"=>1, "E"=>1, "F"=>0, "G"=>0, "H"=>1, "I"=>0, "J"=>0, "K"=>0, "L"=>3, "M"=>0, "N"=>0, "O"=>2, "P"=>0, "Q"=>0, "R"=>1, "S"=>0, "T"=>0, "U"=>0, "V"=>0, "W"=>1, "X"=>0, "Y"=>0, "Z"=>0}




      Finally, to print out the istogram:



      freq.each { |letter, freq| puts "#{letter}: " + "◼︎" * freq if freq > 0 }

      #=> D: ◼︎
      #=> E: ◼︎
      #=> H: ◼︎
      #=> L: ◼︎◼︎◼︎
      #=> O: ◼︎◼︎
      #=> R: ◼︎
      #=> W: ◼︎





      share|improve this answer




























        0












        0








        0







        The main problem is that in calculateFrequencies you are using a not assigned variable: letters. So, when you call calculateFrequencies in display, letters = nil and calling .clear on nil returns the error.



        This is a modified version of the code, using snake_case (which is the Ruby writing standard).



        class LetterHistogram
        attr_accessor :text

        def initialize(t = "Hello World!")
        @text = t
        end

        def display
        calculate_frequencies.each { |letter, freq| puts "#{letter}: #{freq}"}
        end

        private

        def calculate_frequencies
        freq = @text.upcase.gsub!(/W+/, '').each_char.with_object(Hash.new(0)) { |letter, freq| freq[letter] += 1 }
        freq.sort_by{ |letter, freq| freq }.reverse # just to sort
        end
        end


        Instantiating an object and calling .display on it:



        senctence = LetterHistogram.new
        senctence.display

        #=> L: 3
        #=> O: 2
        #=> D: 1
        #=> R: 1
        #=> W: 1
        #=> E: 1
        #=> H: 1


        How it works



        For calculating the frequency I used a Hash populated by: https://ruby-doc.org/core-2.5.1/Enumerable.html#method-i-each_with_object



        Printing out freq from calculate_frequencies you can see it:



        #=> {"H"=>1, "E"=>1, "L"=>3, "O"=>2, "W"=>1, "R"=>1, "D"=>1}





        Alternatively, if you want also not used letters, you can initialise the freq hash with all values to 0, then update the hash, something like this:

        freq = ("A".."Z").each_with_object({}) { |letter, freq| freq[letter] = 0 }
        "Hello World!".upcase.gsub!(/W+/, '').each_char { |letter| freq[letter] += 1 }

        #=> {"A"=>0, "B"=>0, "C"=>0, "D"=>1, "E"=>1, "F"=>0, "G"=>0, "H"=>1, "I"=>0, "J"=>0, "K"=>0, "L"=>3, "M"=>0, "N"=>0, "O"=>2, "P"=>0, "Q"=>0, "R"=>1, "S"=>0, "T"=>0, "U"=>0, "V"=>0, "W"=>1, "X"=>0, "Y"=>0, "Z"=>0}




        Finally, to print out the istogram:



        freq.each { |letter, freq| puts "#{letter}: " + "◼︎" * freq if freq > 0 }

        #=> D: ◼︎
        #=> E: ◼︎
        #=> H: ◼︎
        #=> L: ◼︎◼︎◼︎
        #=> O: ◼︎◼︎
        #=> R: ◼︎
        #=> W: ◼︎





        share|improve this answer















        The main problem is that in calculateFrequencies you are using a not assigned variable: letters. So, when you call calculateFrequencies in display, letters = nil and calling .clear on nil returns the error.



        This is a modified version of the code, using snake_case (which is the Ruby writing standard).



        class LetterHistogram
        attr_accessor :text

        def initialize(t = "Hello World!")
        @text = t
        end

        def display
        calculate_frequencies.each { |letter, freq| puts "#{letter}: #{freq}"}
        end

        private

        def calculate_frequencies
        freq = @text.upcase.gsub!(/W+/, '').each_char.with_object(Hash.new(0)) { |letter, freq| freq[letter] += 1 }
        freq.sort_by{ |letter, freq| freq }.reverse # just to sort
        end
        end


        Instantiating an object and calling .display on it:



        senctence = LetterHistogram.new
        senctence.display

        #=> L: 3
        #=> O: 2
        #=> D: 1
        #=> R: 1
        #=> W: 1
        #=> E: 1
        #=> H: 1


        How it works



        For calculating the frequency I used a Hash populated by: https://ruby-doc.org/core-2.5.1/Enumerable.html#method-i-each_with_object



        Printing out freq from calculate_frequencies you can see it:



        #=> {"H"=>1, "E"=>1, "L"=>3, "O"=>2, "W"=>1, "R"=>1, "D"=>1}





        Alternatively, if you want also not used letters, you can initialise the freq hash with all values to 0, then update the hash, something like this:

        freq = ("A".."Z").each_with_object({}) { |letter, freq| freq[letter] = 0 }
        "Hello World!".upcase.gsub!(/W+/, '').each_char { |letter| freq[letter] += 1 }

        #=> {"A"=>0, "B"=>0, "C"=>0, "D"=>1, "E"=>1, "F"=>0, "G"=>0, "H"=>1, "I"=>0, "J"=>0, "K"=>0, "L"=>3, "M"=>0, "N"=>0, "O"=>2, "P"=>0, "Q"=>0, "R"=>1, "S"=>0, "T"=>0, "U"=>0, "V"=>0, "W"=>1, "X"=>0, "Y"=>0, "Z"=>0}




        Finally, to print out the istogram:



        freq.each { |letter, freq| puts "#{letter}: " + "◼︎" * freq if freq > 0 }

        #=> D: ◼︎
        #=> E: ◼︎
        #=> H: ◼︎
        #=> L: ◼︎◼︎◼︎
        #=> O: ◼︎◼︎
        #=> R: ◼︎
        #=> W: ◼︎






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 17 '18 at 4:51

























        answered Nov 17 '18 at 4:21









        iGianiGian

        5,1192725




        5,1192725
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347190%2fruby-calculate-the-frequencies-of-the-string-text-letters%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python