Begin/end doesn't behave as expected

I think a case statement will do what you want here…

···

On Tue, 19 Nov 2002 10:25:04 GMT, Tim Bates news@bates.id.au wrote:

Why doesn’t this snippet of code do what I expect it to?

out = “<a href="”
out << begin
“error.rb”
“rules.rb” if rule.instance_of? Rule
“dead.rb” if rule.instance_of? DeadRule
“proposals.rb” if rule.instance_of? Proposal
page.to_s unless page.nil?
end
out << “">” + rule.to_s + “”

I expect the begin/end block to evaluate to one of page.to_s,
“proposals.rb”, “dead.rb”, “rules.rb” or if all else fails “error.rb” but
instead it seems to evaluate to nil, and I get “TypeError: failed to
convert nil into String”.

Tim Bates

For the original message, which is not in [ruby-talk]

Why doesn't this snippet of code do what I expect it to?

out = "<a href=\""
out << begin
       "error.rb"
       "rules.rb" if rule.instance_of? Rule
       "dead.rb" if rule.instance_of? DeadRule
       "proposals.rb" if rule.instance_of? Proposal
       page.to_s unless page.nil?
end

The block return the value of the last expression which in this case is

    page.to_s unless page.nil?

  i.e.

    unless page.nil?
       page.to_s
    else
       nil
    end

because probably (???) page is nil, it return the value of the `else' part

I think a case statement will do what you want here..

yes

Guy Decoux

···

On Tue, 19 Nov 2002 10:25:04 GMT, Tim Bates <news@bates.id.au> wrote:

[…]

I think a case statement will do what you want here…

How would I use a case statement here? I’m comparing two different things,
namely rule.instance_of? and page.nil?
[…]
out << begin
“error.rb”
“rules.rb” if rule.instance_of? Rule
“dead.rb” if rule.instance_of? DeadRule
“proposals.rb” if rule.instance_of? Proposal
page.to_s unless page.nil?
end

out << if page then
page.to_s
else
case rule # Note: not rule.type
when Proposal then “proposals.rb”
when DeadRule then “dead.rb”
when Rule then “rules.rb”
else “error.rb”
end
end

Untested, but you get the idea.

[…]

		Reimer Behrends
···

Tim Bates (news@bates.id.au) wrote: