Forum: Ruby Bug in ruby (1.8.7) hash: assignment executes code

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.
Karl W. (Guest)
on 2009-01-18 15:15
(Received via mailing list)
Tested with: ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-linux]

#!/usr/bin/env ruby

$VERBOSE = true

test_hash=Hash["value" => exit]
puts "Never get's executed."


exit is executed and stops the application. Is this a wanted behavior?
Shouldn't an error be thrown like:
  NameError: undefined local variable or method `exit' for
  main:Object

This bug can't be abused for luck:

userinput='%x[nc -lp 1234 -e /bin/bash]'
test_hash=Hash["value" => userinput]

Doesn't work because userinputs gets automatically threated like a
string. Nevertheless I think this isn't a good behavior or?
Jan D. (Guest)
on 2009-01-18 16:33
(Received via mailing list)
On Sunday 18 January 2009 14:13:50 removed_email_address@domain.invalid wrote:
> exit is executed and stops the application. Is this a wanted behavior?
Yes.

> Shouldn't an error be thrown like: NameError: undefined local variable or
> method `exit' for
>   main:Object
>
But this function (exit) *does* exist.

> Doesn't work because userinputs gets automatically threated like a string.
> Nevertheless I think this isn't a good behavior or?

I think you misunderstood what that does. {X => Y} is equivalent to

h = {}
h[X] = Y

that is, it assigns  to hash result of expression Y. In your case the
expression is calling function exit(), then assigning return value of
the
function to the hash. Since exit doesn't return and terminates the
program, it
is kind of nonsensical statement, nevertheless correct. It's the same
as:

def current_time
  return  Time.now
end

test_hash = Hash["value" => current_time]


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