Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Hashes Creating Hashes

is always necesary to use Hash.new {proc} when creating a proc?

Hello I see that when you want to create a proc you use this syntax

yourHash = Hash.new {|hash, key| hash[hey]= "some value for #{key}"}

but for example I now that you can create a hash just using the curly braces instead of use "Hash.new"

So my question is, if is possible to create a proc without to use "Hash.new"

I tried this but it did not work

yourHash = {|hash, key| hash[hey]= "some value for #{key}"}

Thanks

3 Answers

Hi Sabastian

In Ruby, you don't create a proc using Hash.new. You create a proc by calling Proc.new and passing a block. For example: myproc = Proc.new{}.

Alternate syntax allows you to create a proc by using the keyword proc and passing in a block. For example: myproc = proc{}

Hope this helps!

Best,

Ronald

Jessica Barnett
Jessica Barnett
8,028 Points

This is more of an extended question than an answer....

How is it that you're able to create / use a proc by calling Hash.new {} then? Are the Hash and Proc objects related somehow?

Why is it that you're not able to do something like this:

my_hash = {} { |hash, key| hash[hey]= "some value for #{key}" } 

If the {} and Hash.new do basically the same thing - return an empty hash - then why is the behavior different when you try to use a proc with them?

Jessica -

Check out this Stackoverflow.com thread about setting a hash's default_proc: http://stackoverflow.com/questions/20158213/ruby-hash-creating-a-default-value-for-non-existing-elements

Ronald