[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Weird variable scope behaviour...

Randy R

9/22/2007 10:32:00 PM

I just wrote some code that shouldn't have worked, in my estimation, but
it did, anyway. While this was a pleasant surprise, I prefer to understand
why things don't work than to wonder why they did work...

What was happening is this situation, here:


if false
variable = true
end

if variable
#do something
end


To my surprise, this is okay! Even though the code in the first
if-clause doesn't get run, the variable in the clause gets created,
anyway...
Now, I'm pretty sure this is expected behaviour. What I'm wondering is
how people feel about this. This behaviour makes me feel uneasy. If I'm
using a variable that hasn't been deliberately created then I'd rather have
the interpreter complain that I haven't created the variable, as planned,
than to be confused as to why my variable is nil.
I'm very interested to hear other opinions on the subect. Anyone care
to comment?
Thank you...




18 Answers

7stud 7stud

9/22/2007 11:21:00 PM

0

Just Another Victim wrote:
> if false
> variable = true
> end
>
> if variable
> #do something
> end
>
>
> To my surprise, this is okay!


What do you mean by "okay"? Does the following not work as you would
expect:


if false
x = 10
end

if x
puts "yep"
else
puts "nope"
end


Also, see here:

http://www.ruby-...topic/...
--
Posted via http://www.ruby-....

7stud 7stud

9/22/2007 11:23:00 PM

0

7stud -- wrote:
> What do you mean by "okay"?

Ok, I see:

> This behaviour makes me feel uneasy. If
> I'm
> using a variable that hasn't been deliberately created then I'd rather
> have
> the interpreter complain that I haven't created the variable, as
> planned,
> than to be confused as to why my variable is nil.
--
Posted via http://www.ruby-....

7stud 7stud

9/22/2007 11:36:00 PM

0

7stud -- wrote:
> Does the following not work as you would
> expect:
>
>
> if false
> x = 10
> end
>
> if x
> puts "yep"
> else
> puts "nope"
> end
>

Ah. I see what you are concerned about:

if y
puts "yep"
else
puts "nope"
end

undefined local variable or method `y' for main:Object (NameError)




--
Posted via http://www.ruby-....

Phrogz

9/23/2007 3:18:00 AM

0

On Sep 22, 4:32 pm, "Just Another Victim of the Ambient Morality"
<ihates...@hotmail.com> wrote:
> I just wrote some code that shouldn't have worked, in my estimation, but
> it did, anyway. While this was a pleasant surprise, I prefer to understand
> why things don't work than to wonder why they did work...
>
> What was happening is this situation, here:
>
> if false
> variable = true
> end
>
> if variable
> #do something
> end
>
> To my surprise, this is okay! Even though the code in the first
> if-clause doesn't get run, the variable in the clause gets created,
> anyway...
> Now, I'm pretty sure this is expected behaviour. What I'm wondering is
> how people feel about this. This behaviour makes me feel uneasy. If I'm
> using a variable that hasn't been deliberately created then I'd rather have
> the interpreter complain that I haven't created the variable, as planned,
> than to be confused as to why my variable is nil.
> I'm very interested to hear other opinions on the subect. Anyone care
> to comment?
> Thank you...

I understand the behavior, and I've learned to live with it. But (as
I've noted on numerous occassions) I really don't like the reverse
side effect, that you can't write:
p foo if foo=true
even though you can write:
if foo=true then p foo; end

That two statements that are semantically identical should result in
different behavior when foo has not previously been assigned a value
is an unfortunate side effect/tradeoff of the implementation details
and choices.

I accept it in the same way I accept that arrays and hashes have, in
some cases, traded purity for speed. It ain't perfect, but it's what
we got.

Randy R

9/24/2007 2:03:00 AM

0


"7stud --" <dolgun@excite.com> wrote in message
news:c84036c062811fa759eb9e680dfd75a6@ruby-forum.com...
> 7stud -- wrote:
>> Does the following not work as you would
>> expect:
>>
>>
>> if false
>> x = 10
>> end
>>
>> if x
>> puts "yep"
>> else
>> puts "nope"
>> end
>>
>
> Ah. I see what you are concerned about:
>
> if y
> puts "yep"
> else
> puts "nope"
> end
>
> undefined local variable or method `y' for main:Object (NameError)

I'm not sure, exactly, what I'm concerned about but I can give you some
clues.
It's a little weird that the above code with variable y results in a
name error but the previous example with variable x simply results in a nil
object reference. It seems as if they should both result in a nil object
reference or they should both result in a name error, rather than being
inconsistent with each other.
The most pragmatic example of a problem, that I can think of, is a
situation where you have a bug that's immediately caused by a variable
that's unexpectedly nil. Now, you have to trace back the life of the
variable, which can traverse many different scopes, to hopefully discover
that there was an execution path that didn't initialize the variable.
Instead, wouldn't it have been nice if the interpreter simply told you, at
the variable's first use, that it didn't exist 'cause it wasn't initialized?
Now that I put it this way, I think I see how its current behaviour is
an implementation detail, done for increasing speed, leaking through the
interface...




Randy R

9/24/2007 2:06:00 AM

0


"Phrogz" <phrogz@mac.com> wrote in message
news:1190517508.484095.170340@k79g2000hse.googlegroups.com...
>
> I understand the behavior, and I've learned to live with it. But (as
> I've noted on numerous occassions) I really don't like the reverse
> side effect, that you can't write:
> p foo if foo=true
> even though you can write:
> if foo=true then p foo; end
>
> That two statements that are semantically identical should result in
> different behavior when foo has not previously been assigned a value
> is an unfortunate side effect/tradeoff of the implementation details
> and choices.
>
> I accept it in the same way I accept that arrays and hashes have, in
> some cases, traded purity for speed. It ain't perfect, but it's what
> we got.

I'm interested in to what you're referring, here. How was purity of
arrays and hashes compromised for speed?
Thank you...


Phrogz

9/24/2007 3:00:00 AM

0

On Sep 23, 8:05 pm, "Just Another Victim of the Ambient Morality"
<ihates...@hotmail.com> wrote:
> "Phrogz" <phr...@mac.com> wrote in message
> > I accept it in the same way I accept that arrays and hashes have, in
> > some cases, traded purity for speed. It ain't perfect, but it's what
> > we got.
>
> I'm interested in to what you're referring, here. How was purity of
> arrays and hashes compromised for speed?

Things like the fact that Hash and Array literals don't call their
#initialize method, or that all Array methods that fetch values from
the array don't fall back on a single method that one can intercept or
override.

Slackjaw

5/1/2011 12:25:00 PM

0

D?nk 666 wrote:

> On Apr 30, 10:35?pm, "6004 Dead, 1147 since 1/20/09" <d...@gone.com>
> wrote:
> >
http://www.rollingstone.com/politics/blogs/national-affairs......
> > honest-budget-proposal-20110428
> > ...
> > Here, some highlights:
> >
> > New Investments (Cost: $1.7 trillion)
> >
> > ? Job-creating public investments, largely infrastructure ?
> > highways, public transportation, high-speed rail; $1.5 trillion
> > spent in the first five years to combat high unemployment
>
> China spends nothing on combating unemployment, and enjoys nearly full
> employment (Chinese who don't work are shot, and as a result, always
> manage to find jobs). As for infrastructure improvements, this is
> what Chairman Obama promised his trillion-dollar "stimulus" package
> would be used for. The money seems to have vanished into thin air,
> producing neither infrastructure nor employment, and now you demanding
> twice as much money.
>
>
> > Defense Cuts (Savings: $2.3 trillion)
> >
> > ? Cuts off funding for the Iraq and Afghanistan wars.
>
> That was one of Chairman Obama's campaign promises, but rather than
> end the two wars, he decided to continue them, and started a third war
> with Libya.
>
>
> > ? Downsizes the military: Cuts Army and Marine Corps active duty
> > personnel cut by nearly 30 percent; reduces the Navy's fleet size
> > by 20 percent; grounds 15 percent of Air Force squadrons; cancels
> > wasteful weapons systems, including the infamous Osprey and the
> > Expeditionary Fighting Vehicle; and cuts funding for nukes, missile
> > defense, and space weapons
>
> Cutting military jobs means replacing them with other subsidized
> jobs. However much you may dislike it, the U.S. military is the only
> reason we haven't been invaded by China. Perhaps this is why you
> object to it so much.
>
>
> > Increased Taxes (New revenue: $2.8 trillion)
> >
> > ? Revokes the Bush tax cuts ? for everybody ? in 2012, with the
> > exception of a few, targeted tax credits/fixes for married couples
> > and families with children. Extension of Bush tax cuts for the
> > wealthiest ? a highlight of the lame-duck budget deal ? is rescinded
>
> You mean the "lame-duck budget deal" that Chairman Obama signed into
> law? Whatever its form, any tax increase will apply to "the rich,"
> meaning everyone who earns more money than yourself.
>
>
>
> > ? Taxes capital gains and dividends as normal income. Ends
> > preferential tax treatment of investment income
>
> You wouldn't know a capital gain if it bit you on your fat ass.
>
>
> > ? Creates new tax brackets for millionaires and billionaires.
> > Brackets range from 45% for mere millionaires to 49% for those with
> > incomes surpassing $1 billion
>
> And 0% for deadbeat Canadian parasites like yourself.
>
>
> > ? Creates a progressive estate tax: Excludes 99.75% of estates,
> > farms, and small businesses from inheritance taxes. Marginal rates
> > for the top 0.25% of estates range from 45% for a $10 million
> > estate, to 65% for those worth more than half a billion dollars
>
> A truly "progressive" tax would include negative rates for those who
> consume more in public services than they pay in taxes. In other
> words, if you earn $1000 a year selling beaded necklaces on the
> sidewalk, but receive $10,000 in food stamps and housing credits, you
> would have to pay a 50% tax on your $9,000 in virtual income.
>
>
> > ? Taxes U.S. corporations' "foreign" profits as they're earned.
> > Prevents corporations from stockpiling income in foreign shelters
> > by taxing profits abroad, not just when they're repatriated
>
> That's a good way to chase the few remaining American companies
> offshore.
>
>
> > ? Pays to index alternative minimum tax to inflation (The AMT is an
> > alternative tax structure originally meant to ensure that rich tax
> > evaders pay their fair share. But because it was never indexed to
> > inflation, every year more and more middle class taxpayers are hit
> > subject to the tax. Congress has yearly "patched" this flaw in the
> > AMT on an ad hoc basis, adding unbudgeted billions to the deficit.)
>
> According to Chairman Obama's Consumer Price Index, there is no
> inflation. The skyrocketing food and gasoline prices are figments of
> your imagination.
>
>
> > ? Imposes "leverage" taxes on megabanks with assets in excess of $50
> > billion and new taxes on derivatives investors and other Wall Street
> > speculators
>
> Why would Chairman Obama seek to penalize the same banks he voted to
> bail out to the tune of $1 trillion?
>
>
> > ? Limits value of itemized deductions to 28%. Superrich no longer
> > get a sweeter deal for charitable giving
>
> I disapprove of "charitable" deductions, simply because charity is
> giving freely with no expectation of reward, such as a tax deduction.
> However, your proposal contradicts Obama's "faith-based" initiative,
> in which public money is given to private religious "charities" with
> no consent from the taxpayers.
>
>
> > ? Adds 25-cents a gallon to the federal gas tax. Reinvests proceeds
> > in highway infrastructure
>
> Lie. Any new gasoline tax will be spent on crack, and money to repair
> roads will be borrowed from China as usual.
>
>
> > Safety Net (New revenue: $1.2 trillion)
> >
> > ? Raises the maximum income subject to Social Security payroll
> > taxes to $170,000
>
> The additional tax revenues will be spent on crack, leaving Socialist
> Insecurity as insolvent as before.
>
>
>
> > Health Reforms (Savings: $308 billion)
> >
> > ? Creates a 'public option' in health care exchanges.
> >
> > ? Empowers Uncle Sam to negotiate lower prescription drug costs for
> > Medicare.
> >
> > ? Pays for the "doc fix." (In 2002, Congress passed a pay cut for
> > Medicare providers that everyone agrees is too Draconian. By habit,
> > Congress prefers to pass ad-hoc spending bills to forestall the cut,
> > adding unbudgeted billions to the deficit.)
> >
> > Interest Savings (savings: $856.3 billion)
>
> These numbers are completely fictitious. As we have seen in the past,
> actual costs for government programs have always exceeded projected
> costs by two or three times.

The liberals' answer for everthing _. raise taxes and increase spending.

--
-Slackjaw

If ignorance is bliss, why are there so many miserable liberals?

David Hartung

5/1/2011 1:05:00 PM

0

On 05/01/2011 07:25 AM, Slackjaw wrote:
> D?nk 666 wrote:
>
>> On Apr 30, 10:35 pm, "6004 Dead, 1147 since 1/20/09"<d...@gone.com>
>> wrote:
>>>
> http://www.rollingstone.com/politics/blogs/national-affairs......
>>> honest-budget-proposal-20110428
>>> ...
>>> Here, some highlights:
>>>
>>> New Investments (Cost: $1.7 trillion)
>>>
>>> ? Job-creating public investments, largely infrastructure ?
>>> highways, public transportation, high-speed rail; $1.5 trillion
>>> spent in the first five years to combat high unemployment
>>
>> China spends nothing on combating unemployment, and enjoys nearly full
>> employment (Chinese who don't work are shot, and as a result, always
>> manage to find jobs). As for infrastructure improvements, this is
>> what Chairman Obama promised his trillion-dollar "stimulus" package
>> would be used for. The money seems to have vanished into thin air,
>> producing neither infrastructure nor employment, and now you demanding
>> twice as much money.
>>
>>
>>> Defense Cuts (Savings: $2.3 trillion)
>>>
>>> ? Cuts off funding for the Iraq and Afghanistan wars.
>>
>> That was one of Chairman Obama's campaign promises, but rather than
>> end the two wars, he decided to continue them, and started a third war
>> with Libya.
>>
>>
>>> ? Downsizes the military: Cuts Army and Marine Corps active duty
>>> personnel cut by nearly 30 percent; reduces the Navy's fleet size
>>> by 20 percent; grounds 15 percent of Air Force squadrons; cancels
>>> wasteful weapons systems, including the infamous Osprey and the
>>> Expeditionary Fighting Vehicle; and cuts funding for nukes, missile
>>> defense, and space weapons
>>
>> Cutting military jobs means replacing them with other subsidized
>> jobs. However much you may dislike it, the U.S. military is the only
>> reason we haven't been invaded by China. Perhaps this is why you
>> object to it so much.
>>
>>
>>> Increased Taxes (New revenue: $2.8 trillion)
>>>
>>> ? Revokes the Bush tax cuts ? for everybody ? in 2012, with the
>>> exception of a few, targeted tax credits/fixes for married couples
>>> and families with children. Extension of Bush tax cuts for the
>>> wealthiest ? a highlight of the lame-duck budget deal ? is rescinded
>>
>> You mean the "lame-duck budget deal" that Chairman Obama signed into
>> law? Whatever its form, any tax increase will apply to "the rich,"
>> meaning everyone who earns more money than yourself.
>>
>>
>>
>>> ? Taxes capital gains and dividends as normal income. Ends
>>> preferential tax treatment of investment income
>>
>> You wouldn't know a capital gain if it bit you on your fat ass.
>>
>>
>>> ? Creates new tax brackets for millionaires and billionaires.
>>> Brackets range from 45% for mere millionaires to 49% for those with
>>> incomes surpassing $1 billion
>>
>> And 0% for deadbeat Canadian parasites like yourself.
>>
>>
>>> ? Creates a progressive estate tax: Excludes 99.75% of estates,
>>> farms, and small businesses from inheritance taxes. Marginal rates
>>> for the top 0.25% of estates range from 45% for a $10 million
>>> estate, to 65% for those worth more than half a billion dollars
>>
>> A truly "progressive" tax would include negative rates for those who
>> consume more in public services than they pay in taxes. In other
>> words, if you earn $1000 a year selling beaded necklaces on the
>> sidewalk, but receive $10,000 in food stamps and housing credits, you
>> would have to pay a 50% tax on your $9,000 in virtual income.
>>
>>
>>> ? Taxes U.S. corporations' "foreign" profits as they're earned.
>>> Prevents corporations from stockpiling income in foreign shelters
>>> by taxing profits abroad, not just when they're repatriated
>>
>> That's a good way to chase the few remaining American companies
>> offshore.
>>
>>
>>> ? Pays to index alternative minimum tax to inflation (The AMT is an
>>> alternative tax structure originally meant to ensure that rich tax
>>> evaders pay their fair share. But because it was never indexed to
>>> inflation, every year more and more middle class taxpayers are hit
>>> subject to the tax. Congress has yearly "patched" this flaw in the
>>> AMT on an ad hoc basis, adding unbudgeted billions to the deficit.)
>>
>> According to Chairman Obama's Consumer Price Index, there is no
>> inflation. The skyrocketing food and gasoline prices are figments of
>> your imagination.
>>
>>
>>> ? Imposes "leverage" taxes on megabanks with assets in excess of $50
>>> billion and new taxes on derivatives investors and other Wall Street
>>> speculators
>>
>> Why would Chairman Obama seek to penalize the same banks he voted to
>> bail out to the tune of $1 trillion?
>>
>>
>>> ? Limits value of itemized deductions to 28%. Superrich no longer
>>> get a sweeter deal for charitable giving
>>
>> I disapprove of "charitable" deductions, simply because charity is
>> giving freely with no expectation of reward, such as a tax deduction.
>> However, your proposal contradicts Obama's "faith-based" initiative,
>> in which public money is given to private religious "charities" with
>> no consent from the taxpayers.
>>
>>
>>> ? Adds 25-cents a gallon to the federal gas tax. Reinvests proceeds
>>> in highway infrastructure
>>
>> Lie. Any new gasoline tax will be spent on crack, and money to repair
>> roads will be borrowed from China as usual.
>>
>>
>>> Safety Net (New revenue: $1.2 trillion)
>>>
>>> ? Raises the maximum income subject to Social Security payroll
>>> taxes to $170,000
>>
>> The additional tax revenues will be spent on crack, leaving Socialist
>> Insecurity as insolvent as before.
>>
>>
>>
>>> Health Reforms (Savings: $308 billion)
>>>
>>> ? Creates a 'public option' in health care exchanges.
>>>
>>> ? Empowers Uncle Sam to negotiate lower prescription drug costs for
>>> Medicare.
>>>
>>> ? Pays for the "doc fix." (In 2002, Congress passed a pay cut for
>>> Medicare providers that everyone agrees is too Draconian. By habit,
>>> Congress prefers to pass ad-hoc spending bills to forestall the cut,
>>> adding unbudgeted billions to the deficit.)
>>>
>>> Interest Savings (savings: $856.3 billion)
>>
>> These numbers are completely fictitious. As we have seen in the past,
>> actual costs for government programs have always exceeded projected
>> costs by two or three times.
>
> The liberals' answer for everthing _. raise taxes and increase spending.

Along with cutting the military.

Proud Liberal Bitch

5/1/2011 2:24:00 PM

0

Because SlackJaw, we have to listen to morons like you every day.
You don't know your head from you ass
but you spew Fox BS day & night without having the foggiest notion
what you are talking about. You are
the fffffing idiot who has voted against your own best interests for
years.




> -Slackjaw
>
> If ignorance is bliss, why are there so many miserable liberals?- Hide quoted text -
>
> - Show quoted text -