Forum: Ruby Problem with block

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Andy (Guest)
on 2006-05-07 05:49
Why does the following method return nil?

def foo
  info = "           What    |Removed                     |Added
----------------------------------------------------------------------------
                       Status|RESOLVED                    |CLOSED
         "
   result = Hash.new
   info.each do |line|
     if line.scan(/\|/)
       field, oldVal, newVal = line.chomp.split(/\s*\|\s*/)
       if (field == 'Status')
         result['status'] = newVal
       end
     end
   end
   result
end

Also, for some reason the statement "if (field == 'Status')" doesn't
return true.

Thanks,

Andy.
Lloyd Z. (Guest)
on 2006-05-07 06:20
(Received via mailing list)
Andy <removed_email_address@domain.invalid> writes:

>        field, oldVal, newVal = line.chomp.split(/\s*\|\s*/)
>        if (field == 'Status')
>          result['status'] = newVal
>        end
>      end
>    end
>    result
> end

You are not invoking the function "foo", just defining it.  Therefore,
none of the code within "foo" gets executed.  If you invoke foo after
the final "end" statement, you will see a non-nil result.


> Also, for some reason the statement "if (field == 'Status')" doesn't
> return true.

The regular expression passed to the line.chomp.split method does not
cause the leading spaces to get stripped out of the string stored in
"field" ... just any trailing spaces that might exist (of which there
are none).  Therefore, you should do this:

  if (field.strip == 'Status')

... or something similar.
Andy (Guest)
on 2006-05-07 07:03
Lloyd Z. wrote:
> The regular expression passed to the line.chomp.split method does not
> cause the leading spaces to get stripped out of the string stored in
> "field" ... just any trailing spaces that might exist (of which there
> are none).  Therefore, you should do this:
>
>   if (field.strip == 'Status')
>
> ... or something similar.

Adding strip to split statement does the trick
'line.chomp.strip.split'

Thanks for the help,

Andy.
This topic is locked and can not be replied to.