3 Replies - 1962 Views - Last Post: 01 April 2016 - 05:03 AM Rate Topic: -----

#1 nick094  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 30-March 16

Beginner's question

Posted 01 April 2016 - 04:36 AM

Hello felas. I'm new to programming (relatively),but i'm strong willed to learn it. I don't wanna skip stuff that i don't understand,so i'll just write it here.
puts "write a string"
text = gets.chomp
words = text.split
frequency = Hash.new(0)
words.each (|item| frequencies[item]  += 1)
frequencies = frequencies.sort_by (|item,amount| amount)
frequencies.each do |item,amount|
puts.item + " " +amount.to_string
end


Here have a code,but i don't understand why do i need "frequency = Hash.new(0)". The rest of the code seems to me pretty okay.
Thanks :)

Is This A Good Question/Topic? 0
  • +

Replies To: Beginner's question

#2 xclite  Icon User is offline

  • I wrote you an code
  • member icon


Reputation: 1237
  • View blog
  • Posts: 4,029
  • Joined: 12-May 09

Re: Beginner's question

Posted 01 April 2016 - 04:39 AM

By using Hash.new(0), you're setting the default value of any object in that Hash to 0. That way frequencies[item] += 1 Will properly refer to a number when you encounter "item" for the first time.

Also this code won't work, because you initialize the variable as "frequency" but reference "frequencies" later.
Was This Post Helpful? 2
  • +
  • -

#3 ndc85430  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 590
  • View blog
  • Posts: 2,484
  • Joined: 13-June 14

Re: Beginner's question

Posted 01 April 2016 - 04:40 AM

Look at the documentation for Hash here. That tells you what you need to know.
Was This Post Helpful? 3
  • +
  • -

#4 nick094  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 30-March 16

Re: Beginner's question

Posted 01 April 2016 - 05:03 AM

View Postxclite, on 01 April 2016 - 04:39 AM, said:

By using Hash.new(0), you're setting the default value of any object in that Hash to 0. That way frequencies[item] += 1 Will properly refer to a number when you encounter "item" for the first time.

Also this code won't work, because you initialize the variable as "frequency" but reference "frequencies" later.



Thank you, that was helpful. I was wondering why would i use that line.

View Postndc85430, on 01 April 2016 - 04:40 AM, said:

Look at the documentation for Hash here. That tells you what you need to know.



Thanks,great stuff. And great content for someone who wants to learn.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1