String method to take subsections

194 views
Skip to first unread message

Glenn

unread,
Mar 12, 2008, 8:18:00 PM3/12/08
to
[Note: parts of this message were removed to make it a legal post.]

Hi,

I'm looking for a method for the String class that returns an array of strings based on two input strings.

For example, if you had the string 'xxxxxa1byyyyya2bzzzzzzz' I'd like it to return the smaller strings between 'a' and b', but I don't want the smaller strings to include either 'a' or 'b'.

So, 'xxxxxa1byyyyya2bzzzzzzz'.method_x('a', 'b') would return ["1", "2"].

If you had the string 'a1b2' and tried 'a1b2'.method_x('a', 'c') you'd get nil because 'c' is obviously not in the String that's calling the method.

Likewise, if you tried 'a1b2'.method_x('b', 'a') it would also return nil since there's no string between 'b' and 'a' (so the order matters).

I looked but didn't see anything quite like this.

Thanks!

Glenn

David A. Black

unread,
Mar 12, 2008, 8:53:16 PM3/12/08
to
Hi --

Have a look at String#scan.

'xxxxxa1byyyyya2bzzzzzzz'.scan(/a(.*?)b/)
=> [["1"], ["2"]]

It may not be an exact fit for the calling syntax you want but you
could wrap it in something else.


David

--
Upcoming Rails training from David A. Black and Ruby Power and Light:
ADVANCING WITH RAILS, April 14-17 2008, New York City
CORE RAILS, June 24-27 2008, London (Skills Matter)
See http://www.rubypal.com for details. Berlin dates coming soon!

Thomas Wieczorek

unread,
Mar 12, 2008, 8:59:55 PM3/12/08
to
On Thu, Mar 13, 2008 at 1:18 AM, Glenn <glenn...@yahoo.com> wrote:
>
> So, 'xxxxxa1byyyyya2bzzzzzzz'.method_x('a', 'b') would return ["1", "2"].
>

You could use String#scan and wrap it in a method or extend the String class:

# So, 'xxxxxa1byyyyya2bzzzzzzz'.method_x('a', 'b') would return ["1", "2"].

def method_x(str, first, last)
pattern = "#{first}(\\d)#{last}"
regexp = Regexp.new(pattern)
return str.scan(regexp).flatten
end

p method_x('xxxxxa1byyyyya2bzzzzzzz', 'a', 'b') #=> ["1", "2"].

# you could also extend the String class
class String
def method_x(first, last)
pattern = "#{first}(\\d)#{last}"
regexp = Regexp.new(pattern)
return self.scan(regexp).flatten
end
end

p 'xxxxxa1byyyyya2bzzzzzzz'.method_x('a', 'b')

Paul Mckibbin

unread,
Mar 12, 2008, 9:41:26 PM3/12/08
to
Glenn wrote:
> Hi,
>
> I'm looking for a method for the String class that returns an array of
> strings based on two input strings.

Regular expressions are your friend here:

class String
def containedby(startmark='a',endmark='b')
self.scan(Regexp.new(startmark+'([^'+endmark+']*)'+endmark)).flatten
end
end

should do what you want. If you want to restrict it to just one
character remove the * in ']*)'.

> If you had the string 'a1b2' and tried 'a1b2'.method_x('a', 'c') you'd
> get nil because 'c' is obviously not in the String that's calling the
> method.
>
> Likewise, if you tried 'a1b2'.method_x('b', 'a') it would also return
> nil since there's no string between 'b' and 'a' (so the order matters).
>

Actually returns [] in both these cases, but I'm sure you can deal with
those.

Test Listing and output below:
====================================
class String
def containedby(startmark='a',endmark='b')
self.scan(Regexp.new(Regexp.escape(startmark)+'([^'+Regexp.escape(endmark)+']*)'+Regexp.escape(endmark))).flatten
end
end

TEST='xxxxxa1byyyyya2bzzzzzzz'
extracted=TEST.containedby('a','b')
puts extracted.inspect
extracted=TEST.containedby('a','c')
puts extracted.inspect
TEST2='b1a2'
extracted=TEST2.containedby('a','b')
puts extracted.inspect

=====================================

["1", "2"]
[]
[]
--
Posted via http://www.ruby-forum.com/.

Glenn

unread,
Mar 13, 2008, 9:14:36 AM3/13/08
to
[Note: parts of this message were removed to make it a legal post.]

Thanks for your help, guys. All three suggestions are great.

It seems to me that returning an empty array instead of nil is actually better.

Glenn

Paul Mckibbin

unread,
Mar 13, 2008, 4:51:04 PM3/13/08
to
Glenn wrote:
> Thanks for your help, guys. All three suggestions are great.
>
> It seems to me that returning an empty array instead of nil is actually
> better.

I'd be inclined to agree, although some might argue that a test for nil
is easier.

class String
def containedby(startmark='a',endmark='b')

x=self.scan(Regexp.new(Regexp.escape(startmark)+'([^'+Regexp.escape(endmark)+']*)'+Regexp.escape(endmark))).flatten
x.size > 0 ? x : nil
end
end

would return the error conditions as nil.

Mac

Glenn

unread,
Mar 15, 2008, 2:07:27 PM3/15/08
to
It did help. That was exactly it -- I had named the file fastercvs.rb. When I renamed it, it worked fine.

Thanks for your help,

Glenn

----- Original Message ----
From: James Gray <ja...@grayproductions.net>
To: ruby-talk ML <ruby...@ruby-lang.org>

Sent: Saturday, March 15, 2008 10:35:23 AM
Subject: Re: Error using FasterCSV

On Mar 15, 2008, at 7:29 AM, Glenn wrote:

> Hi,

Hello.

> I am trying to use FasterCSV and am getting an error.

Sorry to hear that. I'll try to provide some guesses…

> I installed the fastercsv gem and it appeared to install correctly.
>
> This is the error that I'm getting:
>
> ../fastercsv.rb:3: uninitialized constant FasterCSV (NameError)
> from C:/Program Files/Ruby/lib/ruby/site_ruby/1.8/rubygems/
> custom_require.rb:27:in `gem_original_require'
> from C:/Program Files/Ruby/lib/ruby/site_ruby/1.8/rubygems/
> custom_require.rb:27:in `require'
> from fastercsv.rb:1

That error is a little strange because it is complaining about a lack
of a FasterCSV constant in the require. The file you required though,
fastercsv.rb, does not have a FasterCSV constant anywhere in it.
(It's a shim that loads some other code.)

My guess is this: you named your own file fastercsv.rb. When you try
to require the gem, Ruby is finding your file first and it fails to
load because FasterCSV was never defined. If I'm right, you just need
to rename your file and it will work.

Hope that helps.

James Edward Gray II


Mike Blackwell

unread,
Apr 7, 2008, 4:28:55 PM4/7/08
to
From: Sreedhar Kesanasetti <kesanasett...@citigroup.com>
>> Unlike Java why does not ruby specify the method parameter types.

Because, unlike Java, Ruby is not a strongly typed language.

>> How can a caller know what type of parameter is the method expecting.

Read the method's documentation?


Avdi Grimm

unread,
Apr 7, 2008, 4:43:33 PM4/7/08
to
On Mon, Apr 7, 2008 at 4:28 PM, Mike Blackwell <mai...@sbcglobal.net> wrote:
> Because, unlike Java, Ruby is not a strongly typed language.

To be pedantic, both Java and Ruby are strongly typed. However, Java
is statically types, and Ruby is dynamically typed.

--
Avdi

Phillip Gawlowski

unread,
Apr 7, 2008, 5:12:06 PM4/7/08
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Ruby is?

irb(main):001:0> t = String.new
=> ""
irb(main):002:0> t.class
=> String
irb(main):003:0> t = 1
=> 1
irb(main):004:0> t.class
=> Fixnum
irb(main):005:0> exit

Doesn't look like it to me, since I can change the type of a variable
with ease.

- --
Phillip Gawlowski
Twitter: twitter.com/cynicalryan

Rule of Open-Source Programming #37:

Duplicate effort is inevitable. Live with it.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkf6jiUACgkQbtAgaoJTgL9AOgCfU5pDjiz+K1RP35cLhk9xZnlz
63AAoIKEeH+TUqC82uUoIHke3v+FpnzW
=9FdL
-----END PGP SIGNATURE-----

Iñaki Baz Castillo

unread,
Apr 7, 2008, 5:25:07 PM4/7/08
to
El Lunes, 7 de Abril de 2008, Phillip Gawlowski escribió:
> Avdi Grimm wrote:
> | On Mon, Apr 7, 2008 at 4:28 PM, Mike Blackwell <mai...@sbcglobal.net>
>
> wrote:
> |> Because, unlike Java, Ruby is not a strongly typed language.
> |
> | To be pedantic, both Java and Ruby are strongly typed. However, Java
> | is statically types, and Ruby is dynamically typed.
>
> Ruby is?
>
> irb(main):001:0> t = String.new
> => ""
> irb(main):002:0> t.class
> => String
> irb(main):003:0> t = 1
> => 1
> irb(main):004:0> t.class
> => Fixnum
> irb(main):005:0> exit
>
> Doesn't look like it to me, since I can change the type of a variable
> with ease.

No, look at the following example:

irb(main):001:0> text = "The number is: "
=> "The number is: "

irb(main):002:0> number = 25
=> 25

irb(main):003:0> puts text + number
TypeError: can't convert Fixnum into String
from (irb):3:in `+'
from (irb):3
from :0

--
Iñaki Baz Castillo

Avdi Grimm

unread,
Apr 7, 2008, 5:25:16 PM4/7/08
to
On Mon, Apr 7, 2008 at 5:12 PM, Phillip Gawlowski
<cmdja...@googlemail.com> wrote:
> Ruby is?

>
> Doesn't look like it to me, since I can change the type of a variable
> with ease.

You're confusing static typing and strong typing.

In a weakly-typed language, like C, it is possible to cast an integer
as a, for instance, a char*, and then call string functions like
sprintf() on it and the compiler will compile it, the runtime will run
it, and it will wreak whatever havoc you please. Most high-level
languages are strongly-typed, these days - neither Java or Ruby will
allow you to call a String method on an Integer. You can assign
whatever object you want to a variable in Ruby - hence *dynamic*
typing - but that object will only ever allow you to call supported
methods on it; otherwise you'll get a NoMethodError. Hence *strong*
typing.

--
Avdi

Phillip Gawlowski

unread,
Apr 7, 2008, 6:53:00 PM4/7/08
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Thanks for the enlightenment. :)

- --
Phillip Gawlowski
Twitter: twitter.com/cynicalryan

Zmodem has bigger bits, softer blocks, and tighter ASCII.


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkf6pcwACgkQbtAgaoJTgL9trwCghb7DYangJvsq/ktpceHh12FD
004AnikbmUhG0gwWUJywu43qfbPa76sK
=b6S6
-----END PGP SIGNATURE-----

Robert Klemme

unread,
Apr 8, 2008, 5:08:09 PM4/8/08
to
On 08.04.2008 00:53, Phillip Gawlowski wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Avdi Grimm wrote:
> | On Mon, Apr 7, 2008 at 5:12 PM, Phillip Gawlowski
> | <cmdja...@googlemail.com> wrote:
> |> Ruby is?
> |>
> |> Doesn't look like it to me, since I can change the type of a variable
> |> with ease.
> |
> | You're confusing static typing and strong typing.
> |
> | In a weakly-typed language, like C, it is possible to cast an integer
> | as a, for instance, a char*, and then call string functions like
> | sprintf() on it and the compiler will compile it, the runtime will run
> | it, and it will wreak whatever havoc you please. Most high-level
> | languages are strongly-typed, these days - neither Java or Ruby will
> | allow you to call a String method on an Integer. You can assign
> | whatever object you want to a variable in Ruby - hence *dynamic*
> | typing - but that object will only ever allow you to call supported
> | methods on it; otherwise you'll get a NoMethodError. Hence *strong*
> | typing.
> |
>
> Thanks for the enlightenment. :)

Another way to put it would be that Ruby's variables are type-less,
while objects do have a specific type. While we're at it: type !=
class. Basically the type is defined by all operations (aka methods)
usable on an instance - not the class it was created from.

Kind regards

robert

Mike Blackwell

unread,
Apr 8, 2008, 5:32:37 PM4/8/08
to
Avdi Grimm wrote:
> To be pedantic, both Java and Ruby are strongly typed. However, Java
> is statically types, and Ruby is dynamically typed

Indeed. I stand linguistically admonished. ^_^

Rajat Garg

unread,
Apr 12, 2008, 8:55:56 PM4/12/08
to
[Note: parts of this message were removed to make it a legal post.]

I have a form on a page *add_flight.rhtml -*
<%=form_tag({:controller=>"local_flights",:action=>"shared"},
{:id=>"add_flight", :method=>"post"})%>
....
<%=submit_tag("Add your Flight Request")%>
</form>

Then,* in controller - *
def shared
_flt = params[:fltAvailable]
if !_flt.blank?
@flt = SharedLocalFlight.new(_flt)
@flt.save
end
@fltSharedList = SharedLocalFlight.find(:all)
end

>> This seems to be getting called and then shared.rhtml gets rendered

However, record doesn't get saved to table. There is no error msg in
development.log.

In Shared controller, I rendered params.yaml to see where the issue is -

--- !map:HashWithIndifferentAccess
commit: List your Flight
action: shared
fltAvailable: !map:HashWithIndifferentAccess
from_airport: BFI
cost_type: Cost per person

num_seats: "3"
estimated_flying_time: "1:00"
estimated_cost: "45"
model_name: ""
return_time: 9:00 AM
description: lslkdslks
mfr_name: ""

from_time: 9:00 AM
return_date: "2008-04-16"
from_date: "2008-04-11"
to_airport: HQM
aircraft_id: "73838"
flight_type: One Way


controller: local_flights


I still can't figure out the issue. I will really appreciate if you
can help spot any discrepancy.

--
Rajat Garg


Ph: 206-499-9495
Add: 1314 Spring Street, #412
Seattle, WA 98104
Web: http://www.pilotoutlook.com
Aircraft I have flown:
738VJ<http://www.pilotoutlook.com/aircraft/CESSNA/172N/738VJ>
-----------------------------------------------------------------------------------------------------
Flying is the second greatest thrill known to man. Landing is the first!

f...@andersground.net

unread,
Apr 18, 2008, 6:11:40 AM4/18/08
to
|-----BEGIN PGP SIGNED MESSAGE-----
|Hash: SHA1
|
|Vio Dds wrote:
|| Hi,
||
|| I'm trying to redirect my redmine page :
||
|| I have my web site url : http://www.mywebsite.eu
|| and I try to put redmine on http://www.mywebsite.eu/redmine
||
|| but I can't !
||
|| I put in 'http_vhosts.conf' a redirection proxy
||
|| proxypass /redmine http://localhost:3000/redmine
|| proxypassreverse /redmine http://localhost:3000/redmine
||
|| So now my first page works properly put when I go to another page : 404
|| Error Page not found.
||
|| Can you please tell what I did wrong or what I should add ?
|
|Check the manual and other support sites for your webserver.

|
|- --
|Phillip Gawlowski
|Twitter: twitter.com/cynicalryan

If RTFM is the only thing that you have to say: keep it to yourself. Manual and support won't help him here, because he is obviously on a wrong track.

So, Vio. We had a similar problem a while ago.

The problem is that you application is mapped at "/" on your local webserver (localhost:3000). So, the proxypass has to read:

======
proxypass /redmine http://localhost:3000
proxypassreverse /redmine http://localhost:3000
======

This however gives you another problem: redmine will begin to generate URLs that are mapped to "/". So links won't work. You have to tell redmine what it's relative url root is:

======
ActionController::AbstractRequest.relative_url_root = "/redmine"
======

Put this in one of the environment files after the frameworks are loaded.

Greetings
Skade

Phillip Gawlowski

unread,
Apr 18, 2008, 6:31:42 AM4/18/08
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

f...@andersground.net wrote:

| If RTFM is the only thing that you have to say: keep it to yourself.
Manual and support won't help him here, because he is obviously on a
wrong track.

This is the Ruby Talk mailing list, not a mailing list for redmine
(http://www.redmine.org/), nor the Rails mailing list
(http://www.ruby-forum.com/forum/3). Asking for configuration details of
an unspecified webserver (Mongrel cluster? Litespeed? mod_rails?
WEBrick?) is better done at the locations that are actually concerned
with that.

The chances of finding somebody who can actually help increases extremely.

Especially if the crystal ball is cloudy.

- --
Phillip Gawlowski
Twitter: twitter.com/cynicalryan

Youth is the trustee of posterity.
~ -- Benjamin Disraeli


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgIeIoACgkQbtAgaoJTgL9IFwCbBND5AVGoM8UPqtgYeYyGGeFl
kVgAn0Dh4mwWU2VT2MwBszWqfBXh0Hsz
=gM8y
-----END PGP SIGNATURE-----

Florian Gilcher

unread,
Apr 18, 2008, 7:43:59 AM4/18/08
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>


> This is the Ruby Talk mailing list, not a mailing list for redmine
> (http://www.redmine.org/), nor the Rails mailing list
> (http://www.ruby-forum.com/forum/3). Asking for configuration
> details of
> an unspecified webserver (Mongrel cluster? Litespeed? mod_rails?
> WEBrick?) is better done at the locations that are actually concerned
> with that.
>
> The chances of finding somebody who can actually help increases
> extremely.
>
> Especially if the crystal ball is cloudy.
>
> - --
> Phillip Gawlowski
> Twitter: twitter.com/cynicalryan
>

While this is true, your answer would have been more useful if you
actually
provided those references you are providing now. Just answering "well,
read the
manual" without pointing out the flaws of his request is not helpful
and futile.
Your answer only increases Vios frustration which cannot be the goal
of this
mailing list.

Regards,
Florian Gilcher

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)

iEYEARECAAYFAkgIpZQACgkQJA/zY0IIRZb5fgCfYWHr80tAmaNUEWZ1ADZp61D3
oMcAoL54X2JHgvVc2ZLTduUc6aDX8oTm
=pUT0
-----END PGP SIGNATURE-----

Phillip Gawlowski

unread,
Apr 18, 2008, 8:30:10 AM4/18/08
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Florian Gilcher wrote:

| While this is true, your answer would have been more useful if you
actually
| provided those references you are providing now. Just answering "well,
| read the
| manual" without pointing out the flaws of his request is not helpful and
| futile.
| Your answer only increases Vios frustration which cannot be the goal of
| this
| mailing list.


What's next: "How to use a search engine"? "Clicking on links for the
search-engine impaired"? "Can u giv me teh codez for h3ll0 wurld!1111"?

A minimal level of research can be, and should be, expected. And somehow
I suspect that routing issues for a webserver or Rails app or whatever
aren't new problems, either.

If nothing shows up, or nothing really matches the problem, then, by all
means, ask for help.

- --
Phillip Gawlowski
Twitter: twitter.com/cynicalryan

~ Verbing weirds language.
~ --- Calvin.
-----BEGIN PGP SIGNATURE-----


Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgIlEoACgkQbtAgaoJTgL+WWgCfegtWjz+ea+0JzcA1zdois8qH
xOEAnA6zt2Lyrt5qwKYFPWK0wwnJ5gvD
=e0J8
-----END PGP SIGNATURE-----

Florian Gilcher

unread,
Apr 18, 2008, 9:08:37 AM4/18/08
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> What's next: "How to use a search engine"? "Clicking on links for the


> search-engine impaired"? "Can u giv me teh codez for h3ll0 wurld!
> 1111"?
>
> A minimal level of research can be, and should be, expected. And
> somehow
> I suspect that routing issues for a webserver or Rails app or whatever
> aren't new problems, either.
>
> If nothing shows up, or nothing really matches the problem, then, by
> all
> means, ask for help.

My point was: If you think that the question is a null statement,
don't add another
null statement - at least try to improve the value of the thread.
Maybe there is
someone else that can make sense of it.

Regards,
Florian Gilcher

P.S.: But if you could give me teh codez for h3ll0 wurld, i'd be
happy :).
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)

iEYEARECAAYFAkgInUcACgkQJA/zY0IIRZZkBQCgnAlA3CyIm7ofG2f9hpyVqasg
lAwAoJWbtdo5KQ/Ncqm0eE//2eu3BTfA
=i1Ib
-----END PGP SIGNATURE-----

Brandon Hoult

unread,
Apr 21, 2008, 4:39:11 PM4/21/08
to
[Note: parts of this message were removed to make it a legal post.]

I had some issues using active record objects inside the code block. It
seems that activerecord does not allow concurrency by default, and I ended
up with "MySQL server has gone away" messages as a result.

I found a couple of possible fixes here
http://www.ruby-forum.com/topic/123472, and am not sure which one is best to
use.

The first is just to add "ActiveRecord::Base.allow_concurrency = true" which
seems to work fine for me and is certainly the simplest.

The other is to "ActiveRecord::Base.remove_connection" before forkoff! then
"ActiveRecord::Base.establish_connection(dbconfig)" first thing in the code
block, then "ActiveRecord::Base.establish_connection(dbconfig)" after
forkoff.

If the second method is better then it would probably be best added to the
gem. Any advice?

ara.t.howard

unread,
Apr 21, 2008, 6:51:06 PM4/21/08
to

On Apr 21, 2008, at 2:39 PM, Brandon Hoult wrote:
> The other is to "ActiveRecord::Base.remove_connection" before
> forkoff! then
> "ActiveRecord::Base.establish_connection(dbconfig)" first thing in
> the code
> block, then "ActiveRecord::Base.establish_connection(dbconfig)" after
> forkoff.
>
> If the second method is better then it would probably be best added
> to the
> gem. Any advice?

this is purely an active record issue - nothing to do with forkoff.
the ar code doesn't carry itself across a fork - there are a few
patches out there that fix this - one by a guy in denver - can't
recall his name - anyone?

a @ http://codeforpeople.com/
--
we can deny everything, except that we have the possibility of being
better. simply reflect on that.
h.h. the 14th dalai lama


James Koppel

unread,
Apr 23, 2008, 3:14:30 PM4/23/08
to
[Note: parts of this message were removed to make it a legal post.]

Thanks for your work in keeping up RubyQuiz! My spare thinking time has been taken up by other work lately, but this one's simple enough that I feel fairly confident in typing up this solution while away from the nearest computer with a Ruby interpreter installed (browser Ruby didn't work for testing).

As a competition-loving math student, for me the obvious way to calculate the area of a triangle is Hero's formula:

class Vector
def distance(oth)
Math.sqrt(to_a.zip(oth.to_a).inject(0){|s,(a,b)|s+(a-b)**2})
end
end

class Triangle
def area
ab = @a.distance(@b)
bc = @b.distance(@c)
ac = @a.distance(@c)
s = (ab+bc+ac)/2
Math.sqrt(s*(s-ab)*(s-bc)*(s-ac))
end
end


----- Original Message ----
From: Matthew Moss <matthe...@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>

Sent: Saturday, April 19, 2008 11:39:34 AM
Subject: [QUIZ] Triangle Area (#160)

Apologies for the latest... Some busy stuff this week in "real life."
In light of that, I've kept this quiz simple: you only need implement
one function. I do provide brief descriptions of a few possible
techniques, but don't feel you need to do them all! Just pick one that
sounds interesting to you...

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

The three rules of Ruby Quiz 2:

1. Please do not post any solutions or spoiler discussion for this
quiz until 48 hours have passed from the time on this message.

2. Support Ruby Quiz 2 by submitting ideas as often as you can! (A
permanent, new website is in the works for Ruby Quiz 2. Until then,
please visit the temporary website at

<http://matthew.moss.googlepages.com/home>.

3. Enjoy!

Suggestion: A [QUIZ] in the subject of emails about the problem
helps everyone on Ruby Talk follow the discussion. Please reply to
the original quiz message, if you can.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

Quiz #160
Triangle Area


Start with the following code for a Triangle class:

require 'matrix'

RANDOM_PT = lambda { Vector[rand(101)-50, rand(101)-50] }

class Triangle
def initialize(a, b, c)
@a, @b, @c = a, b, c
end

def Triangle.random(foo = RANDOM_PT)
Triangle.new(foo.call, foo.call, foo.call)
end

def [](i)
[@a, @b, @c][i]
end

def area
# Fill in this stub.
end

def inspect
"Triangle[#{@a}, #{@b}, #{@c}]"
end
alias to_s inspect
end


Your task this week is to write the code for the `area` method.

There are a few techniques that come to mind for determining (or
closely
estimating) the area of a triangle. You do not need to attempt all of
these;
just pick a technique that sounds fun and do implement it.


1. Determinant Method

It is possible to calculate the area of a triangle very simply using
just the
points as part of a matrix, and calculating the determinant of that
matrix.
See (http://mathforum.org/library/drmath/view/55063.html) for an
explanation
of the technique. This is quick and easy, so if you don't have much
time this
week, try this.


2. Monte Carlo Method

The Monte Carlo method first requires that you determine a bounding
area
(typically a box) that surrounds the test area (i.e. the triangle).
Then you
choose thousands of random points within the box, determining for each
point
whether it falls inside or outside the triangle.

Knowing the area of the box (an easier calculation) and the percentage
of
random points that fell inside the triangle, you can multiply those
two values
together to get the triangle's area.


3. Scan-Line Method

Imagine covering the triangle with horizontal bars of a certain
height, such
that each bar is only wide enough to hide the triangle underneath.
Knowing
the width and height of each bar (i.e. rectangle) lets you calculate
the area
of each, and summed together is an approximation of the triangle's
area.

(This is sometimes called a scan-line method, as you are examining
horizontal
slices of the subject, very much like a television scan line draws a
number of
horizontal slices of the picture.)

Each time the height of the bars are halved (and twice as many are
employed),
your estimate of the triangle's area will improve. Those familiar with
calculus
will recognize this as integration, as the height of each horizontal
slice
approaches zero.


4. Something else!

If none of these methods interest you, but you have with another
method to
estimate or determine exactly the triangle's area, please do!


____________________________________________________________________________________
Be a better friend, newshound, and
know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ

James Koppel

unread,
Apr 23, 2008, 3:15:11 PM4/23/08
to

Ed Davey

unread,
Apr 24, 2008, 9:48:33 AM4/24/08
to
Hi there,

Ilya Grigorik has posted a series of detailed and practical articles
on supervised learning, decision trees, bayesian filtering etc.

http://www.igvita.com/2008/01/07/support-vector-machines-svm-in-ruby/

Ed

Glenn West

unread,
Apr 28, 2008, 6:26:38 AM4/28/08
to
For me, I find generally ruby is "nice".

1. Easy to do a gui (Either locally or via the web using rails
2. Easy to use a database (In 6 months I've done Oracle, Pervasive, Unify, Firebird, and dbase)
3. Generally easy to "script" to everything from LDAP to telnet and screen scrap the web
4. Easiest to learn (Python was easy to, but the web framework is less mature)
5. I think if you want to do a "exe" py2eye is sweet. I need to find the equiv for ruby
6. Python I think has better graphics libraries (My pcxtojpg didnt require ImageMagik, and is a easy to use command line exe)
7. I hacked a Color Profile with ruby and bitstructs, so hacking packets is pretty easy to

I learned python 18 months ago, I learned ruby 9 months ago. I've not touched python since.

Also check out shoes.

I love ruby so much I even invested in 6 books. (But you dont need them as almost everything is on the web).

If I had any compaint about ruby, its that its "too" easy.
:) Nice problem to have.

- Original Message ----
From: Phillip Gawlowski <cmdja...@googlemail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>

Sent: Monday, 28 April 2008 6:21:00
Subject: Re: Ruby For Hackers

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Luka Lukako wrote:

| Which learn first, python, perl or java? which is more easy?
| 1. python
| 2. perl
| 3. and java?

Yes.

They are all equally easy or hard to learn, nowadays, especially if you
already know your way around technical documentation, or know how to use
a search engine.

(I know that 'Dive into Python' is available for free as electronic
version, which is sort of similar to Programming Ruby).

- --
Phillip Gawlowski
Twitter: twitter.com/cynicalryan

Zero defects: The result of shutting down a production line.
~ -- Kelvin Throop III, "The Management Dictionary"
-----BEGIN PGP SIGNATURE-----


Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkgU/DYACgkQbtAgaoJTgL99rgCgnTUf5QhtIx45IXA7YeVNNT13
vkUAoJlgwKdlhvhEIA+WdLMq+DqBgX7J
=fRDA
-----END PGP SIGNATURE-----


__________________________________________________________________
Yahoo! Singapore Answers
Real people. Real questions. Real answers. Share what you know at http://answers.yahoo.com.sg


Abdul-rahman Advany

unread,
Apr 29, 2008, 5:14:55 PM4/29/08
to
Check out the code for spawn, the guys have fixed this

maestroiu...@yahoo.com

unread,
May 7, 2008, 9:46:06 AM5/7/08
to

----- Original Message ----
> From: VICTOR GOLDBERG <vmgol...@verizon.net>
> To: ruby-talk ML <ruby...@ruby-lang.org>

> Sent: Wednesday, May 7, 2008 1:10:17 PM
> Subject: Interesting result of a newbie mistake
>
> Instead of writing
> a = %w{ ant cat dog }
> I wrote
> a = %{ ant cat dog }

That defines a string.

> puts a[2] --> 110

The reason is that indexing a string in Ruby 1.8 and previous versions returns the character code.
That usually comes as a surprise to beginners. This behavior changes in Ruby 1.9 to return the character (see http://eigenclass.org/hiki.rb?Changes+in+Ruby+1.9#l116).

See the following IRB Ruby 1.8 session:

$ irb
>> a = %{ ant cat dog }
=> " ant cat dog "
>> a.class
a.class
=> String
>> a[2]
a[2]
=> 110
>> a[2].chr
a[2].chr
=> "n"
>>
>
> I didn't find an explanation for this result in Dave Thomas' book
> Anybody volunteers a response?

If you look for the String class and the chr method into the index of the first edition
http://ruby-doc.org/docs/ProgrammingRuby/
you will find examples showing this behavior.

Christophe

>
> Thanks,
> Víctor


VICTOR GOLDBERG

unread,
May 7, 2008, 10:30:03 AM5/7/08
to
Thank you all that responded.
maestroiut's explanation was especially enlightening.

Víctor

================================================

<maestroiu...@yahoo.com> wrote in message
news:112782....@web54305.mail.re2.yahoo.com...

McLaughlin, James T.

unread,
May 13, 2008, 10:14:53 AM5/13/08
to
I am a netbeans junkie, but I do a lot of C++ also. You'll get as many different opionions as editors, I'm afraid.

Jamie
http://blog.thoughthook.com
Jamie McLaughlin
SAIC
Office: 703-292-6307
Mobile: 571-263-2528

----- Original Message -----
From: kittu_...@yahoo.co.in <kittu_...@yahoo.co.in>
To: ruby-talk ML <ruby...@ruby-lang.org>
Sent: Tue May 13 06:03:59 2008
Subject: About Editors


Hi, I have been working on C# from the past two and half years and as a
ruby enthusiast i would like to dig in to it to the extent possible for
me....as of know just a newbie and interested in knowing the best editor
to work with Ruby..
is it Netbeans? or Rad Rails? or may be some other editor...can any one
of you people please suggest me the best editor to work with....

thanks in advance!
kittu.

James Koppel

unread,
May 13, 2008, 9:58:53 PM5/13/08
to
[Note: parts of this message were removed to make it a legal post.]

I was a little late submitting this week, so, rather than fleshing this solution out, I just challenged myself to write a short but good program. I think I did a pretty good job, at 33 lines of non-golfed code.

Thanks to Andrew Johnson and his solution to RubyQuiz 69 for showing me the trick of using hashes for lazy evaluation.

state = nil
instructions = File.open(ARGV[0]) do |f|
f.readlines.map{|s|
(s=s.match(/^[^#]+/)[0].strip).empty? ? nil : s}.compact.
inject({}){|hsh,s|
md=s.match(/(\w+)\s+(\w)\s+(\w+)\s+(\w)\s+([LR])/)
state = state || md[1]
hsh[[md[1],md[2]]]=[md[3],md[4],md[5]]
hsh
}
end

tape = Hash.new do |cell,v|
h = cell.dup
h[:C] = '_'
h[v=='L' ? 'R' : 'L'] = cell
cell[v] = h
end

tape[:C] = '_'
ARGV[1].to_s.split(//).reverse.each{|c|tape=tape['L'];tape[:C]=c}

until instructions[[state,tape[:C]]].nil?
state, ch, move = instructions[[state,tape[:C]]]
tape[:C] = ch
tape = tape[move]
end

tape = tape['L'] while tape.keys.include? 'L'
output = [tape[:C]]
(tape = tape['R']; output << tape[:C]) while tape.keys.include? 'R'

puts output.reject{|c|c=='_'}.join

----- Original Message ----
From: Matthew Moss <matthe...@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>

Sent: Friday, May 9, 2008 10:48:40 AM
Subject: [QUIZ] The Turing Machine (#162)

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

The three rules of Ruby Quiz 2:

1. Please do not post any solutions or spoiler discussion for this
quiz until 48 hours have passed from the time on this message.

2. Support Ruby Quiz 2 by submitting ideas as often as you can! (A
permanent, new website is in the works for Ruby Quiz 2. Until then,
please visit the temporary website at

<http://matthew.moss.googlepages.com/home>.

3. Enjoy!

Suggestion: A [QUIZ] in the subject of emails about the problem
helps everyone on Ruby Talk follow the discussion. Please reply to
the original quiz message, if you can.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

## The Turing Machine

_Quiz description by James Edward Gray II_

The Turing Machine is a simple computing architecture dating all the
way back to the 1930s. While extremely primitive compared to any
modern machine, there has been a lot of research showing that a Turing
Machine is capable of just about anything the fancier machines can do
(although much less efficiently, of course).

This week's task is to build a Turing Machine, so we can play around
with the architecture.

A Turing Machine has but three simple parts:

* A single state register.
* An infinite tape of memory cells that can hold one character
each, with a
read/write head that points to one of these cells at any given
time. The
tape is filled with an infinite run of blank characters in
either
direction.
* A finite set of program instructions. The program is just a big
table of
state transitions. The Turing Machine will look up an
instruction based
the current value of the state register and the current
character under
head of the tape. That instruction will provide a state for
the
register, a character to place in the current memory cell, and
an order to
move the head to the left or the right.

To keep our Turning Machine simple, let's say that our state register
can contain words matching the regular expression `/\w+/` and the tape
only contains characters that match the expression `/\w/`. We will
call our blank tape cell character the underscore.

Program lines will be of the form:

CurrentState _ NewState C R

The above translates to: if the current state is CurrentState and the
character under the tape head is our blank character, set the state to
NewState, replace the blank character with a C, and move the tape head
to the right one position. All five elements will be present in each
line and separated by one or more whitespace characters. Allow for
trailing comments (using #) on a line, comment only lines, and blank
lines in the program by ignoring all three.

The initial state of your Turing machine should be set to the
CurrentState mentioned on the first line of the program. Optionally,
the initial contents of the tape can be provided when the program is
load, but it will default to an all blank tape. The program runs
until it fails to find an instruction for the CurrentState and the
character currently under the tape head, at which point it prints the
current contents of the tape head from the first non-blank character
to the last non-blank character and exits.

Here's a sample run of a simple program through my Turing Machine so
you can see how this plays out:

$ cat palindrome.tm
# Report whether a string of 0 and 1 (ie. a binary
# number) is a palindrome.
look_first 0 go_end_0 _ R
look_first 1 go_end_1 _ R
look_first _ write_es Y R
go_end_0 0 go_end_0 0 R
go_end_0 1 go_end_0 1 R
go_end_0 _ check_end_0 _ L
go_end_1 0 go_end_1 0 R
go_end_1 1 go_end_1 1 R
go_end_1 _ check_end_1 _ L
check_end_0 0 ok_rewind _ L
check_end_0 1 fail_rewind _ L
check_end_0 _ ok_rewind _ L
check_end_1 0 fail_rewind _ L
check_end_1 1 ok_rewind _ L
check_end_1 _ ok_rewind _ L
ok_rewind 0 ok_rewind 0 L
ok_rewind 1 ok_rewind 1 L
ok_rewind _ look_first _ R
fail_rewind 0 fail_rewind _ L
fail_rewind 1 fail_rewind _ L
fail_rewind _ write_o N R
write_es _ write_s e R
write_o _ done o R
write_s _ done s R

$ ruby tm.rb palindrome.tm 011010110
Yes

$ ruby tm.rb palindrome.tm 01101
No



McLaughlin, James T.

unread,
May 19, 2008, 9:07:27 AM5/19/08
to
I use hpricot for all my XML - to access a node in a doc via XPath, you just do:

node = (doc / "/path/to/node")

The / operator is overloaded to do XPath. Check out the docs first (use google) for the exact syntax. You must explicitly tell hpricot you are parsing xml or it will not work right.


Jamie McLaughlin
SAIC
Office: 703-292-6307
Mobile: 571-263-2528

----- Original Message -----
Sent: Mon May 19 06:40:32 2008
Subject: using Xpath in Ruby

Dear friends,

I want use xpath in my ruby program. could you please suggest some ways
to proceed .?. Some links would help me to do..

I need some some details regarding how its implemented in REXML and
HPRICOT.

Thanks in advance..

Regards,
Jose

rubisher

unread,
May 20, 2008, 8:01:55 AM5/20/08
to
Hello Marcin,

> self.class.to_s should work
>
>
Sorry this return me the class name itself not the instance name?

e.g.
#!/usr/bin/env ruby

class Investment
def initialize
puts "I'am ALIVE!"
iname=self.class.to_s
puts "Instance Name: #{iname}"
end
end

_Invest = Investment.new

puts _Invest.class

give me:
I'am ALIVE!
Instance Name: Investment
Investment

and not "Instance Name: _Invest" as am looking for.

Tx,
r.

Yoshikane Noguchi

unread,
May 21, 2008, 4:00:18 AM5/21/08
to
受信確認レポート

件名: Re: BasicObject & OpenStruct in Ruby 1.8.7-preview3

開封者: Yoshikane Noguchi/scm

日付: 2008/05/21 16:53:59

Robert Klemme

unread,
May 21, 2008, 5:33:01 AM5/21/08
to
2008/5/20 rubisher <rubi...@scarlet.be>:

There is no such thing as an instance name - unless you define a
property of your class called "name". Each instance can be referenced
by any number of variables including 0 - there is simply not _the_
name. As Inaki pointed out.

Kind regards

robert

--
use.inject do |as, often| as.you_can - without end

rubisher

unread,
May 23, 2008, 4:39:07 PM5/23/08
to
Robert Klemme wrote:
> 2008/5/20 rubisher <rubi...@scarlet.be>:
>> Hello Marcin,
>>
>>> self.class.to_s should work
>>>
>>>
>> Sorry this return me the class name itself not the instance name?
>>
>> e.g.
>> #!/usr/bin/env ruby
>>
>> class Investment
>> def initialize
>> puts "I'am ALIVE!"
>> iname=self.class.to_s
>> puts "Instance Name: #{iname}"
>> end
>> end
>>
>> _Invest = Investment.new
>>
>> puts _Invest.class
>>
>> give me:
>> I'am ALIVE!
>> Instance Name: Investment
>> Investment
>>
>> and not "Instance Name: _Invest" as am looking for.
>
> There is no such thing as an instance name - unless you define a
> property of your class called "name".
Ok what I did.
The idea was that as far as ruby is interpreded, it have to save variable name somewhere in clear with its id and for
debuging reason it could be accessible somehow. But ok it's not possible and for me it's just nice to know.

> Each instance can be referenced
> by any number of variables including 0 - there is simply not _the_
> name. As Inaki pointed out.
>
> Kind regards
>
> robert
>

Tx to all for feedback,
r.

Phillip Gawlowski

unread,
May 23, 2008, 9:19:36 PM5/23/08
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

rubisher wrote:

| The idea was that as far as ruby is interpreded, it have to save
| variable name somewhere in clear with its id and for debuging reason it
| could be accessible somehow. But ok it's not possible and for me it's
| just nice to know.

Well, you could modify your MyClass#initialize method to do something
similar.

Add a global variable or something similar, and add the object to this
variable (for example a Hash, with the variable name as key, and the
object's class as value).

Though, you'd have to intercept the assignment somehow to grab the
variable name.

HTH,


- --
Phillip Gawlowski
Twitter: twitter.com/cynicalryan

Blog: http://justarubyist.blogspot.com

Format a program to help the reader understand it.
~ - The Elements of Programming Style (Kernighan & Plaugher)


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkg3bS8ACgkQbtAgaoJTgL/bPwCfRra/JfzsjjD5XS9cRXdB7Ede
RRUAn3eYv1QZQnWHIIzVixr1hm1eDwUR
=vkQ1
-----END PGP SIGNATURE-----

rubisher

unread,
May 24, 2008, 4:49:34 PM5/24/08
to
Phillip Gawlowski wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> rubisher wrote:
>
> | The idea was that as far as ruby is interpreded, it have to save
> | variable name somewhere in clear with its id and for debuging reason it
> | could be accessible somehow. But ok it's not possible and for me it's
> | just nice to know.
>
> Well, you could modify your MyClass#initialize method to do something
> similar.
>
> Add a global variable or something similar, and add the object to this
> variable (for example a Hash, with the variable name as key, and the
> object's class as value).
>
Good, very good idea, I will investigate.

> Though, you'd have to intercept the assignment somehow to grab the
> variable name.
>

Thanks a lot,
r.

Reidmix

unread,
May 29, 2008, 7:55:54 PM5/29/08
to
[Note: parts of this message were removed to make it a legal post.]

you are just assigning a to an array literal
This is equivalent to
a = Array.new(['one','two','three'])
Like Siep said, array access a[0] will raise the error.
r


----- Original Message ----
From: Siep Korteling <s.kor...@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>

Sent: Thursday, May 29, 2008 3:28:45 PM
Subject: Re: Quickie: Monkey patching Array

Leon Bogaert wrote:
> I know it's bad behaviour :) But I'm just fiddling with ruby.
>
> class Array
> def [](elem) # just get rid of the "="
> raise 'Yesss... It works!'
> end
> end
>
> a = ['one', 'two', 'three']
> p a
>
> Didn't work also. It just prints: ["one", "two", "three"]

try

p a[0]


[] is just a method. You chanced it. To verify if your change works, you
'll have to use the [] method. If this is not what you want, what
outcome did you expect?

regards,

Siep

f...@andersground.net

unread,
May 30, 2008, 6:08:34 AM5/30/08
to
Actually, i had such a problem. You problem is
the adress normalization. We solved it by using an external resource:
google maps - they are really good at that.

When someone enters an address, you do a call to google maps to
retrieve the coodinates of an address and save the together with the adress.

When someone enters a search string, you call google again to retrieve the
coordinates and then you search you database for addresses with coordinates
that are within a certain radius.

If you know what your doing and you use a good geocoding-lib, thats about 20-30 lines of code for both operations.

Regards,
Florian Gilcher

McLaughlin, James T.

unread,
Jun 4, 2008, 5:01:54 PM6/4/08
to




Here is the info:

Address: 209.128.121.112



The user account is saic, the password is What@pain2




Jamie McLaughlin
SAIC
Office: 703-292-6307
Mobile: 571-263-2528

----- Original Message -----
Sent: Wed Jun 04 12:33:22 2008
Subject: ruby-ftp - directory vs file?

How do I find out whether "foobar" is a remote directory, or a remote
file?

I don't seem to find any trivial way to check this.
Has this maybe been forgotten?

McLaughlin, James T.

unread,
Jun 4, 2008, 5:04:22 PM6/4/08
to

McLaughlin, James T.

unread,
Jun 4, 2008, 5:06:10 PM6/4/08
to











Jamie McLaughlin
SAIC
Office: 703-292-6307
Mobile: 571-263-2528

----- Original Message -----
From: bbxx78...@yahoo.com <bbxx78...@yahoo.com>
To: ruby-talk ML <ruby...@ruby-lang.org>
Sent: Tue Jun 03 00:38:02 2008
Subject: Re: general query about ruby libraries

Sandip Gangakhedkar wrote:
> Hi all,
>
> I would like to know where exactly to unpack external ruby libraries for
> future use. I'm using aaronp's mechanize library (zip file)...and it
> uses the require 'mechanize' directive.
>
> Thanks,
> Sandip

I think the generally accepted way to install a 3rd party library is to
use RubyGems:

"RubyGems is a standardized packaging and installation framework for
libraries and applications, making it easy to locate, install, upgrade,
and uninstall Ruby packages." pickaxe2 p 215.

That's what I do. You need to install RubyGems and learn how to use it.

McLaughlin, James T.

unread,
Jun 4, 2008, 5:06:16 PM6/4/08
to

McLaughlin, James T.

unread,
Jun 4, 2008, 5:07:27 PM6/4/08
to

McLaughlin, James T.

unread,
Jun 4, 2008, 5:18:04 PM6/4/08
to
EW
$

McLaughlin, James T.

unread,
Jun 4, 2008, 5:19:13 PM6/4/08
to


Jamie McLaughlin
SAIC
Office: 703-292-6307
Mobile: 571-263-2528

----- Original Message -----
From: s.kor...@gmail.com <s.kor...@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>
Sent: Tue Jun 03 04:00:44 2008
Subject: Re: Safe sandbox for running untrusted code

Ruben Fonseca wrote:
> ara.t.howard wrote:
>> On Jun 2, 2008, at 9:12 AM, Ruben Fonseca wrote:
>>
>>> It this possible with the current VM (MRI 1.8)?
>>
>> no.
>>
>> you will need to combine using $SAFE=12 (ruby side) and ulimit/chroot
>> from the unix side (or similar).
>
> hi! thanks for all your input!
>
> so does anybody knows how http://tryruby.hobix.com/ does it?
>
> Ruben


http://www.spoj.pl/info/ does this with 30 programming languages,
including Ruby. I don't know how.

regards,

Siep

McLaughlin, James T.

unread,
Jun 4, 2008, 5:33:29 PM6/4/08
to
Qq
Jamie McLaughlin
SAIC
Office: 703-292-6307
Mobile: 571-263-2528

----- Original Message -----
From: anukul....@gmail.com <anukul....@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>
Sent: Tue Jun 03 05:46:19 2008
Subject: Killing Win32 process

Hi,

I tried the following code snippet to kill a Win32 process:

def killQTP
wmi = WIN32OLE.connect("winmgmts://")
processes = wmi.ExecQuery("select * from Win32_process")
for process in processes do
if process.Name.include? "QTPro.exe" then
puts "Name: #{process.Name}"
puts "Process ID: #{process.Pid}"
puts process.Terminate
elsif process.Name.include? "star.exe" then
puts "Name: #{process.Name}"
puts "Process ID: #{process.Pid}"
puts process.Terminate
end
end
puts "done killing QTP"
end

But the process is not getting killed when I execute the above and
simply gives "exit code: 0"

Can anyone help in case I am missing anything to execute the above code
or is there any other way of killing a Win32 process?

Thanks,
Anukul

Phillip Gawlowski

unread,
Jun 4, 2008, 5:37:23 PM6/4/08
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

McLaughlin, James T. wrote:
|
|
|
| Here is the info:
|
| Address: 209.128.121.112
|
|
|
| The user account is saic, the password is What@pain2

Change the password. Now.

Do you know what it's like alone, really alone? [They gave me] weapons,
shelter, food -- everything I needed to live -- except companionship ...
~ to send me here alone -- if that is not death, what is?
~ -- Zarabeth of Sarpeidon, "All Our Yesterdays," stardate 5943.9.


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkhHC1kACgkQbtAgaoJTgL+X3gCdEEr8mk4ZOw6l6v7u5CgisQE0
B/EAnA4eYOplJgFvuGvPlZqFgJQ1dWQb
=J683
-----END PGP SIGNATURE-----

McLaughlin, James T.

unread,
Jun 6, 2008, 10:27:50 PM6/6/08
to
You can use env to get the value of $STAT from ruby. Please forgive me if I miss some details here but....

Try this:

puts ENV["STAT"]

That should print the value of the env variable named STAT. I am not sure how changes to the var by a script called by the ruby prog are reflected in the current env hash - check the docs there may be an env.reload method.
Jamie McLaughlin
SAIC
Office: 703-292-6307
Mobile: 571-263-2528

----- Original Message -----
From: irina.a...@gmail.com <irina.a...@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>
Sent: Fri Jun 06 18:51:40 2008
Subject: Trying to get a value from cshell script inside ruby

I am trying to run the c shell script inside ruby script.
Looks something like this:

csh_script = File.new(TemporaryFile.getFileName("test_csh"), w)
csh_script.puts("#!/bin/csh/")
csh_script.chmod(0555)
csh_script.puts(" ls -l | wc -l") #some command here
csh_script.puts("$STAT = $?")
csh_script.puts("exit($STAT)")
csh_script.close

#then call smth like this in order to execute the script

system(csh_script.path)


What I am trying to get is the value of the $STAT to get passed in to
the ruby script and assigned to some variable

I would appreciate any help

James Koppel

unread,
Jun 8, 2008, 10:50:07 AM6/8/08
to
[Note: parts of this message were removed to make it a legal post.]

This sounds a lot like the Stable Marriage Problem.


----- Original Message ----
From: Matthew Moss <matthe...@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>

Sent: Friday, June 6, 2008 12:43:43 PM
Subject: [QUIZ] Preferable Pairs (#165)

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

The three rules of Ruby Quiz 2:

1. Please do not post any solutions or spoiler discussion for this
quiz until 48 hours have passed from the time on this message.

2. Support Ruby Quiz 2 by submitting ideas as often as you can! (A
permanent, new website is in the works for Ruby Quiz 2. Until then,
please visit the temporary website at

<http://splatbang.com/rubyquiz/>.

3. Enjoy!
Suggestion: A [QUIZ] in the subject of emails about the problem
helps everyone on Ruby Talk follow the discussion. Please reply to
the original quiz message, if you can.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

## Preferable Pairs (#156)

Imagine a pairs tournament: a competition where every player partners up
with another for the duration of the tournament. Everyone plays in a pair
and wins or loses in a pair.

But everyone arrives individually, and only pairs up at the start. Every
player has preferences for a partner; your task is to try and optimize those
preferences as best as possible.

The input is a series of lines containing names, such as:

David: Helen Vicki Joseph
Helen: David Vicki Joseph
Joseph: Vicki Helen David
Vicki: David Helen Joseph

Each line represents the preferences of the first named player (i.e. before
the colon). That player's preferred parters are listed after the colon, in
order of preference (i.e. most preferred first, least preferred last).

The output of your code should be the pairings, one pair per line. For the
example above, your output should look like this:

David Helen
Joseph Vicki

If an odd number of people were provided at the start, then one person will
be left out. That person's name should be output alone on the last line.

What determines the best pairing? A score will be calculated for your output
against the input. For each player, the partner is found in the player's
ordered list, as an index. So, for the above example:

David: 0
Helen: 0
Joseph: 0
Vicki: 2

Each individual's score is then squared, then all are added together. Here,
the final score is 4. The _lower_ your score, the better the match.

--
Matthew Moss <matthe...@gmail.com>


James Koppel

unread,
Jun 8, 2008, 10:53:35 AM6/8/08
to
[Note: parts of this message were removed to make it a legal post.]

In fact, this *is* the Stable Roommates problem.

Matthew Moss

unread,
Jun 8, 2008, 2:05:05 PM6/8/08
to
> In fact, this *is* the Stable Roommates problem.

Sure looks like it... I probably should have remembered this from
university. I wonder if the scoring method I presented is essentially
equivalent to the stability condition.

Eric Mahurin

unread,
Jun 8, 2008, 2:34:05 PM6/8/08
to
[Note: parts of this message were removed to make it a legal post.]

I don't think this quiz is equivalent to the "stable roommates problem".
The stable roommates problem just wants a local minimum solution. This may
be a reasonable approximation to the problem. I think the "weighted
matching problem" is closer to this quiz. This problem looks to be
NP-complete.

Steven Hahn

unread,
Jun 8, 2008, 10:24:39 PM6/8/08
to

Ok, I think this one will always find the optimal solution, because it is exhaustive. Some people were saying that this is the Stable Roommates problem; I am not familiar with that, but a greedy solution definitely wouldn't work. Also, I agree that this does seem like it is NP-Complete, because greedy does not work and there are O(n!) potential solutions... I believe (n-1)!! to be exact. I didn't put in much in the way of optimizations, so it should not handle a large set of input date. Since, the input is already YAML-ready, the following program expects the input to be a YAML file name.
---------------------------------------------------------------------------------
require 'yaml'

#execute program by providing a file name with the data in YAML format

#Example YAML file contents:

#David: Helen Vicki Joseph

#Helen: David Vicki Joseph

#Joseph: Vicki Helen David

#Vicki: David Helen Joseph


class PairCalculator
def initialize(filename)
#read data into hash from YAML file
@pairs_hash = YAML::load_file(filename)
@num_people = @pairs_hash.length
@num_choices = @num_people - 1

#build array of all possible pairs
@all_pairs = get_all_pairs
end

#finds the nth choice of a person for some value n, 0 would be
#the first choice, 1 second, etc.
def get_nth_choice(person, n)
@pairs_hash[person].scan(/\w+/)[n]
end

#this method returns 0 if the pair is only one name
#otherwise it calculates the sum of the squares of the individual
#preference indexes, 0=best, 1=next best, etc.
def get_pair_value(pair)
pair_array = pair.split(" ")
return 0 if(pair_array.length==1)
return @pairs_hash[pair_array[0]].scan(/\w+/).index(pair_array[1])**2 +
@pairs_hash[pair_array[1]].scan(/\w+/).index(pair_array[0])**2
end

#this method calculates the value of a possible solution of pairs
def get_pair_set_val(pair_set)
val = 0
pair_set.each {|next_pair| val += get_pair_value(next_pair)}
return val
end

#this method calculates a list of pairs from the pair array minus the
#head_pair and any similar pairs (see similar? method for more details).
def get_tail(pair_array, head_pair)
tail_array = []
pair_array.each do |next_pair|
#remove all pairs with common partners
tail_array += [next_pair] unless(similar?(head_pair, next_pair))
end
return tail_array
end

#pairs are considered similar if they share a common name or they
#are both a single name (this case makes sure that only one single
#name can be selected in any given solution
def similar?(pair1, pair2)
#returns true if they are both length of 1
return true if(pair1.split(" ").length==1 and
pair2.split(" ").length==1)

#returns true if the pairs have common partners
pair1.split(" ").each do |next_name|
if(pair2.include?(next_name))
return true
end
end
return false
end

#this method generates a list of all possible pairs
def get_all_pairs
all_pairs = []
@pairs_hash.each_key do |p1|
1.upto(@num_choices) do |cnt|
#select the next person in the list
p2 = get_nth_choice(p1, cnt-1)
all_pairs += [p1 + " " + p2]
end
#add individual names if there are an odd number of people
all_pairs += [p1] if (@num_people & 1 == 1)
end
return all_pairs
end

#this method executes an exhaustive search of all pair sets for
#each set it calculates the value with the best found up to that
#point. if the value is lower then it saves the new solution.
def get_preferred_pairs(pair_array=@all_pairs)
solution = []
solution_value = 1.0/0.0
#base case: pair_array is empty
if(pair_array.length==0)
return solution
end

#iterate over all pairs in the array use each one as the head
#in a potential solution
pair_array.each do |pair|
#get the next potential solution
pair_set = [pair] +
get_preferred_pairs(get_tail(pair_array, pair)) #recursive call
#calculate the value of the next potential solution
pair_set_val = get_pair_set_val(pair_set)
if(solution_value>pair_set_val)
#better solution has been found... save it!
solution = pair_set
solution_value = pair_set_val
end
end
return solution
end
end

if(ARGV.length == 0)
puts "Usage: provide YAML file name as the argument."
exit 0
end

pc = PairCalculator.new(ARGV[0])
pair_set = pc.get_preferred_pairs
pair_set.each {|pair| puts pair}
puts "Pair set value: #{pc.get_pair_set_val(pair_set)}"


_________________________________________________________________
Now you can invite friends from Facebook and other groups to join you on Windows Live™ Messenger. Add now.
https://www.invite2messenger.net/im/?source=TXT_EML_WLH_AddNow_Now

Steven Hahn

unread,
Jun 9, 2008, 6:05:17 PM6/9/08
to

I made a couple of minor optimizations to my solution. It still will not handle large inputs, but it is a little better. Thanks to Eric Ivancich, I removed some of the duplicate checks of potential solutions. I hope I got them all. Also, I added some memoization for values of solution sets, which has the downside of requiring more memory but seems to improve overall performance.

-------------------------------------------------
require 'yaml'

#execute program by providing a file name with the data in YAML format
#Example YAML file contents:
#David: Helen Vicki Joseph
#Helen: David Vicki Joseph
#Joseph: Vicki Helen David
#Vicki: David Helen Joseph

class PairCalculator
def initialize(filename)
#read data into hash from YAML file
@pairs_hash = YAML::load_file(filename)
@num_people = @pairs_hash.length
@num_choices = @num_people - 1

@pair_set_value_hash = Hash.new
@pair_value_hash = Hash.new



#build array of all possible pairs
@all_pairs = get_all_pairs
end

#finds the nth choice of a person for some value n, 0 would be
#the first choice, 1 second, etc.
def get_nth_choice(person, n)
@pairs_hash[person].scan(/\w+/)[n]
end

#this method returns 0 if the pair is only one name

#otherwise it looks up the pair value in a hash


#preference indexes, 0=best, 1=next best, etc.
def get_pair_value(pair)
pair_array = pair.split(" ")
return 0 if(pair_array.length==1)

#get the value from the pair value hash
return @pair_value_hash[pair] + @pair_value_hash[pair_array[1] + " " + pair_array[0]]
end

#this method calculates the value of a possible solution of pairs
def get_pair_set_val(pair_set)

#check the hash first
return @pair_set_value_hash[pair_set] if(@pair_set_value_hash.include?(pair_set))

#not in the hash calculate it


val = 0
pair_set.each {|next_pair| val += get_pair_value(next_pair)}

@pair_set_value_hash[pair_set] = val

#add to all pairs list
all_pairs += [p1 + " " + p2] unless(all_pairs.include?(p2 + " " + p1))

#add to pair_value_hash for later lookup
@pair_value_hash[p1 + " " + p2] = (cnt-1)**2

t1 = Time.now
pc = PairCalculator.new("list.yaml")


pair_set = pc.get_preferred_pairs
pair_set.each {|pair| puts pair}

t2 = Time.now
puts "Pair set value: #{pc.get_pair_set_val(pair_set)} \nTime: #{t2 - t1}"


_________________________________________________________________
Instantly invite friends from Facebook and other social networks to join you on Windows Live™ Messenger.
https://www.invite2messenger.net/im/?source=TXT_EML_WLH_InviteFriends

Eric I.

unread,
Jun 12, 2008, 1:54:13 PM6/12/08
to
Zach Dennis wrote:
> Does anyone else think this is weird behavior in ruby 1.8.x ?
> [].all?{ false } # => true
>
> The implementation of enum.all? defaults the result to true, and then relies
> on iterating over the elements to set it to false. It seems like it should

Daniel Parker wrote:
> I agree, even though the docs do explain exactly what it does, it seems like
> it shouldn't return true. Maybe returning nil would be more appropriate when
> there are no elements.

Craig Demyanovich wrote:
> That the code does what the docs indicate is beside the point (though
> it's good that they're in agreement ;-) ). The behavior is definitely
> not what I would've expected, which is to return false. My vote is to
> just return false when there are no elements. I like to avoid nil
> whenever possible (which is almost always) because it forces client
> code to use a conditional to check for it.

I guess I'm a contrarian here, because I think Ruby's current behavior
is correct, and I think I can make a decent case for it. These kinds
of "edge" conditions can often be counter-intuitive, although if you
look at the larger picture they make perfect sense. Weren't you a
little put off when you first learned that n**0 == 1 (if n != 0)? Or
when you learned that 0! == 1? But if powers and factorials didn't
behave that way, a lot of simple stuff would break (like the formulas
for permutations and combinations).

First, the content of the block is irrelevant as it should never be
executed when the collection is empty. The block Zach uses though is
very well chosen, in that it really strikes his point home.

Second, all? (along with any?) are defined by the Enumerable module,
which is designed to with collections of various sorts, not just
arrays. All a collection has to do is implement the each method, and
Enumerable handles everything else. So the behavior of all? (and
any?) should make sense in this very general context -- including
sets, trees, linked lists, etc.

Third, if *all* members of a collection have a property, then *any
subset* of that collection should have that property. So if I have a
collection of accounts that are all overdue, any subset of those
accounts should be overdue as well, right? And the empty collection
is a valid subset.

[account1, account2, account3].all? { |a| a.overdue? }
=> true
[account1].all? { |a| a.overdue? }
=> true
[].all? { |a| a.overdue? }
=> true

If all? on an empty collection simply returns false, then we lose this
valuable property.

Fourth, there is a symmetry between all? and any?. In fact, it's the
same symmetry we have between && and || using De Morgan's Law:

P && Q == !(!P || !Q)
P || Q == !{!P && !Q)

With all? and any? we have these equivalents:

collection.all? { |member| member.property? } == ! collection.any? {
|member| ! member.property? } # note two inversions
collection.any? { |member| member.property? } == ! collection.all? {
|member| ! member.property? }

Let's take accounts and being overdue as our specific example. If in
a given collection all accounts are overdue, then it *can't* be the
case that *any *of the accounts are *not* overdue:

[account1, account2, account3].all? { |a| a.overdue? } == ! [account1,
account2, account3].any? { |a| ! a.overdue? } # note the two
inversions

Those expressions must be equivalent. And so should this:

[].all? { |a| a.overdue? } == ! [].any? { |a| ! a.overdue? } # note
the two inversions

Changing the behavior of all? would break this identity.

And note that just as:

[].all? { blah }

will always return true:

[].any? { blah }

will always return false.

So even though it seems counter-intuitive at first blush, in the
larger context it makes perfect sense, and it would be a mistake to
change it.

Eric

====

LearnRuby.com offers Rails & Ruby HANDS-ON public & ON-SITE workshops.
Ruby Fundamentals Workshop June 16-18 Ann Arbor, Mich.
Ready for Rails Ruby Workshop June 23-24 Ann Arbor, Mich.
Ruby on Rails Workshop June 25-27 Ann Arbor, Mich.
Ruby Plus Rails Combo Workshop June 23-27 Ann Arbor, Mich.
Please visit http://LearnRuby.com for all the details.

Robert Dober

unread,
Jun 12, 2008, 2:12:03 PM6/12/08