Ruby: hash as argument

What will Ruby do, when we pass hash as argument to function? Let’s see.

We have method – with definied default value (empty hash):

def foo(hashh = {})
  puts 'Is hash empty? ' + hashh.empty?.to_s,""
end

1. When we invoke function with any hash, it will be passed into method. Output? „Is hash empty? false„.

foo({:id => 'someid'})

h = {:id => 'first', :name => 'noname'}
foo(h)

2. When we invoke function without any parameter, Ruby will take default value – empty hash. Output is „Is hash empty? true„.

foo

3. Of course, when we pass nil to function, we will got exception: „undefinied method ’empty’ for nil:NilClass„.

foo(nil)

Przydatny wpis? Postaw mi kawę :)

0 0 votes
Article Rating
Subscribe
Powiadom o
guest
0 komentarzy
Inline Feedbacks
View all comments