Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does Ruby functions return a value even when there is nothing to return?

Below code converts the provided key’s value in an array of hashes from JSON to hash if it is not nil. This is demonstrated in example 1.

In example 2 the provided key is nil therefore no changes are made to the data. This is the behavior I want. However I can’t understand why this is happening. In example 2, the code doesn’t hit line if !hash[key].nil? which means the function must return nil however it appears to be returning data_2. In ruby I understand that functions return the last evaluated statement. In example 2 what exactly is the last evaluated statement?

require 'json'

def convert(arr_of_hashes, key)
    arr_of_hashes.each do |hash|
      if !hash[key].nil?
        begin
          JSON.parse(hash[key])  
        rescue JSON::ParserError => e  
          raise "Bad"
        else
            hash[key] = JSON.parse(hash[key], {:symbolize_names => true})
        end
      end
    end
  end
data_1 = [ { :key_1 => "Apple", :key_2 => "{\"one\":1, \"two\":2}", :key_3 => 200 }, { :key_1 => "Orange" } ]

data_2 = [ { :key_1 => "Apple", :key_2 => nil, :key_3 => 200 }, { :key_1 => "Orange" } ]

# Example 1
p convert(data_1, :key_2)
# [{:key_1=>"Apple", :key_2=>{:one=>1, :two=>2}, :key_3=>200}, {:key_1=>"Orange"}]

# Example 2
p convert(data_2, :key_4)
# [{:key_1=>"Apple", :key_2=>nil, :key_3=>200}, {:key_1=>"Orange"}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Consider an extremely basic example:

irb(main):003:0> a = [1, 2, 3]
=> [1, 2, 3]
irb(main):004:0> a.each { |x| p x }
1
2
3
=> [1, 2, 3]
irb(main):005:0>

The #each method
is returning the Enumerable object.

If I wrap this in a method, the method returns the last expression, which evaluates to the Enumerable object a.

irb(main):006:0> def foo(a)
irb(main):007:1>   a.each { |x| puts x }
irb(main):008:1> end
=> :foo
irb(main):009:0> foo([1, 2, 3])
1
2
3
=> [1, 2, 3]
irb(main):010:0> 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading