Odd module dynamic method behaviour

Hi,

I've been defining modules for mixins with dynamic methods - here is a test module:

module Odd
  A_HASH = Hash[:a=>1, :b=>2]
  AN_ARRAY = [:c, :d]

  puts "hash keys: #{A_HASH.keys}"
  puts "array values: #{AN_ARRAY}"

  A_HASH.keys do |k|
    puts "defining #{k}"
    define_method(k) do
      puts "#{k}"
    end
  end
  AN_ARRAY.each do |k|
    puts "defining #{k}"
    define_method(k) do
      puts "#{k}"
    end
  end
end

puts "methods: #{Odd.instance_methods}"

- The issue is that the A_HASH.keys code does not fire but the AN_ARRAY.each code does as the following shows:

hash keys: [:a, :b]
array values: [:c, :d]
defining c
defining d
methods: [:c, :d]

Any ideas? - I am using ruby 1.9.2 pl180

Regards,

John

Use A_HASH.keys.each instead. It's bitten us all, I suspect.

···

On Jun 5, 2011, at 12:20 PM, John Sanders wrote:

A_HASH.keys do |k|

OK found it

···

On 2011-06-05 17:17:01 +0100, John Sanders said:

Hi,

I've been defining modules for mixins with dynamic methods - here is a test module:

module Odd
  A_HASH = Hash[:a=>1, :b=>2]
  AN_ARRAY = [:c, :d]

  puts "hash keys: #{A_HASH.keys}"
  puts "array values: #{AN_ARRAY}"

  A_HASH.keys.each do |k|
    puts "defining #{k}"
    define_method(k) do
      puts "#{k}"
    end
  end
  AN_ARRAY.each do |k|
    puts "defining #{k}"
    define_method(k) do
      puts "#{k}"
    end
  end
end

puts "methods: #{Odd.instance_methods}"

- The issue is that the A_HASH.keys code does not fire but the AN_ARRAY.each code does as the following shows:

hash keys: [:a, :b]
array values: [:c, :d]
defining c
defining d
methods: [:c, :d]

Any ideas? - I am using ruby 1.9.2 pl180

Regards,

John

Just spotted as you replied thanks - won't forget that one again

···

On 2011-06-05 17:22:10 +0100, Michael Edgar said:

On Jun 5, 2011, at 12:20 PM, John Sanders wrote:

A_HASH.keys do |k|

Use A_HASH.keys.each instead. It's bitten us all, I suspect.