Yield Example in Ruby For Rails book

I am going through the Ruby for Rails book. How do I run the following code:

class C

  def temp_chart(temps)
    for temp in temps
      converted = yield(temp)
      puts "#{temp}\t#{converted}"
    end
  end
  
  celsiuses = [0,10,20,40]
  temp_chart(celsiuses) {|cel| cel * 9 / 5 + 32}
  
end

c = C.new
c.temp_chart(celsiuses)

I am getting error message:

NoMethodError: undefined method ‘temp_chart’ for C:Class

at top level in c.rb at line 11

TIA

You probably want

class C

def temp_chart(temps)

for temp in temps

converted = yield(temp)

puts “#{temp}\t#{converted}”

end

end

end

celsiuses = [0,10,20,40]

c = C.new

c.temp_chart(celsiuses)

I probably can’t explain why very well, but eventually Ruby for Rails will.

Good luck!

Hi --

I am going through the Ruby for Rails book. How do I run the following code:

class C

def temp_chart(temps)
   for temp in temps
     converted = yield(temp)
     puts "#{temp}\t#{converted}"
   end
end

celsiuses = [0,10,20,40]
temp_chart(celsiuses) {|cel| cel * 9 / 5 + 32}

end

c = C.new
c.temp_chart(celsiuses)

I am getting error message:

NoMethodError: undefined method �temp_chart� for C:Class

at top level in c.rb at line 11

Your combining two ways of doing it that don't mix; you want either
this:

   class C
     def something
     end
   end

   c = C.new
   c.something

or this:

   def something
   end

   something

What you're trying to do is like this:

   class C
     def something
     end

     something # won't run in this context; it needs an
                  # instance of C
   end

Also, note that celsiuses is a local variable, so the celsiuses inside
the class definition block won't be the same as the celsiuses outside
it.

David

I ran the code as given in the book:

def temp_chart(temps)
  for temp in temps
    converted = yield(temp)
    puts "#{temp}\t#{converted}"
  end
end
celsiuses = [0,10,20,30,40,50,60,70,80,90,100]
temp_chart(celsiuses) {|cel| cel * 9 / 5 + 32 }

This runs fine. I was under the impression it must be part of a class. I am still confused how I
could use yield from within a class. Where should the yield block be defined?

When I run that code I get:

LocalJumpError: no block given

method temp_chart in c.rb at line 5
method temp_chart in c.rb at line 4

That gave me an idea, ha, this looks like some kind_of? class
initialization... :smiley:

class X
     def self.ordinary_class_method_is_to(&block)
         block.call
     end
     def ordinary_instance_method_is_to(&block)
         block.call
     end

     ordinary_class_method_is_to do
         puts 'Buy bags...'
     end
end

x = X.new
x.ordinary_instance_method_is_to do
     puts 'Give away...'
end

Hi --

I found the fix, the problem is that it was expecting the block: {|cel| cel * 9 / 5 + 32}
after the name. Now it runs fine.