From: "Cédric Finance" Date: 2007-04-20T18:27:25+09:00 Subject: Re: what does this code do ? from libxml schema-test.rb ??? ------=_Part_34557_1529926.1177061243764 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline I think that the block is called only if there is an error or a warning during the validation. Otherwise the block is not called. In case of an error/warning, the block get the message and whether it is an error or a warning. It is possible that the block is called for each warnings and errors. I will check the extension. On 4/20/07, Reuben Grinberg wrote: > > aktxyz@gmail.com wrote: > > At the bottom of the schema-test.rb in the libxml gem, there is this > > bit of code. > > > > This is when I realize I still have a long way to go with Ruby. I > > don't get the {} block right after the 1st line, how does this work, > > its like a {} block in do-end block ? weird. > > > > Of course, what I am after is the message in the case schema > > validation fails ! > > > > > > if doc.validate_schema(schema) { |message, error| puts "#{error ? > > 'error' : 'warning'} : #{message}" } > > puts "validation passed" > > else > > puts "validation failed" > > end > > > > I'm not sure exactly which set of {}'s you are referring to, so I'll > explain all of them. > > In ruby, functions can take as an argument another function to call. > > (More detailed information here > > http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods > > but I'll summarize) > > Here is an example of a function that takes another function as an > argument, and then calls that function: > > irb>def print_it > #yield is a special keyword that calls the passed function > puts yield > end > > irb> print_it { "bob" } > bob > > Furthermore, the function passed in can take an argument: > > irb>def print_it2 > puts yield(3) > end > > irb> print_it { |x| x + 1 } > 4 > > > So in your code, > if doc.validate_schema(schema) { |message, error| > > message is the message from validating and error is the error... > > So if you wanted to make a function that returned the message: > def validate(doc, schema) > doc.validate_schema(schema) { |message, error| return message } > end > > Or, if you want to get the error and message: > > the_message, the_error = nil > if doc.validate_schema(schema) { |message, error| > the_message, the_error = message, error > puts "#{error ? error' : 'warning'} : #{message}" > } > puts "validation passed" > else > puts "validation failed" > end > > > Are you asking about #{message}? > > This is the way to get the value of a variable inside a string: > > irb>a = 5 > irb>puts a > 5 > irb>puts "a" > a > irb>puts "#{a}" > 5 > > irb> greeting = "hello" > irb> puts "#{greeting}, Bob!" > hello Bob! > > Hope that helps, > Reuben > > ------=_Part_34557_1529926.1177061243764--