Home > Software design >  How does Ruby functions return a value even when there is nothing to return?
How does Ruby functions return a value even when there is nothing to return?

Time:06-25

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"}]

CodePudding user response:

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> 
  •  Tags:  
  • ruby
  • Related