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
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!
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')
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/.
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
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
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
>> How can a caller know what type of parameter is the method expecting.
Read the method's documentation?
To be pedantic, both Java and Ruby are strongly typed. However, Java
is statically types, and Ruby is dynamically typed.
--
Avdi
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-----
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
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
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-----
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
Indeed. I stand linguistically admonished. ^_^
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!
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
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-----
>
> 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-----
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-----
> 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-----
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?
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
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
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
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
----- 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
Víctor
================================================
<maestroiu...@yahoo.com> wrote in message
news:112782....@web54305.mail.re2.yahoo.com...
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
> 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.
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
> 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.
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-----
> Though, you'd have to intercept the assignment somehow to grab the
> variable name.
>
Thanks a lot,
r.
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
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. wrote:
|
|
|
| Here is the info:
|
| Address: 209.128.121.112
|
|
|
| The user account is saic, the password is What@pain2
Change the password. Now.
- --
Phillip Gawlowski
Twitter: twitter.com/cynicalryan
Blog: http://justarubyist.blogspot.com
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-----
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>
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.
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.
#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
-------------------------------------------------
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
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.
Cheers
Robert
--
http://ruby-smalltalk.blogspot.com/
---
As simple as possible, but not simpler.
Albert Einstein
Here http://pastie.org/214895
or below (not sure how long pastie keeps the content)
Cheers,
Dave
# http://pastie.org/214895
#
# Ruby Quiz 166 Circles
# David Phillips
#
# sample output
#
# 0000000000000--|||||||||||||||++++++ !!!!!!!!!!!!!!!!!!!!!!!!!
# 00000000000-----|||||||||||||++++++++ !!!!!!!!!!!!!!!!!!!!!!!
# 0000000000------|||||||||||||+++++++++ \ !!!!!!!!!!!!!!!!!!!!!!!
# 000000000--------|||||||||||++++++\\\\\\\\\\\\\!!!!!!!!!!!!!!!!!!!!!!!
# 000000000----------|||||||++++++\\\\\\\\\\\\\\\\\!!!!!!!!!!!!!!!!!!!!
# 00000000-------------------++++\\\\\\\\\\\\\\\\\\\!!!!!!!!!!!!!!!!!
# 000000000-----------------++++\\\\\\\\\\\\\\\\\\\\\!!!!!!!!!!!!!!!
# 000000-----------------+++\\\\\\\\\\\\\\\\\\\\\\\ !!!!!!!!!
# 0 -----------------+++\\\\\\\\\\\\\\\\\\\\\\\===== !
# ------------- \\\\\\\\\\\\\\\\\\\\\\\\\=======
# XXXX--------- \\\\\\\\\\\\\\\\\\\\\\\=========
# XXXXXXXXXX- \\\\\\\\\\\\\\\\\\\\\\\===========
# XXXXXXXXXXXXX ////\\\\\\\\\\\\\\\\\\\\\\\===========*
# XXXXXXXXXXXXX ////////\\\\\\\\\\\\\\\\\\\\\=============*
# XXXXXXXXXXXXXXX //////////\\\\\\\\\\\\\\\\\\\==============**
# XXXXXXXXXXXXX /////////////\\\\\\\\\\\\\\\=================*
# XXXXXXXXXXXXX //////////////\\\\\\\\\\\\\=================**
# XXXXXXXXX /////////////////// \=======================***
# XXXXXXX ///////////////////// =======================**
# /////////////////// *=====================***
# /////////////////// ***=================*****
# ///////////////// ***===============*****
# /////////////// *****=========*******
# ///////////// ********=**********
# / *************
# *
class Canvas
def initialize aspect_ratio=1.6
@rows= []
@y_multiplier= 1/aspect_ratio
yield self if block_given?
end
def set_pixel x, y, char
x, y = x.round, (@y_multiplier*y).round
(@rows[y]||=[])[x]=char unless (x<0 || y<0)
end
def to_s
@rows.map do |row|
row.nil? ? '' : row.map{|c|c||=' '}.join
end.join("\n")
end
# decided to try a method that doesn't require trig functions
def draw_circle x, y, r, fill_char='#'
(x-r)round.upto((x+r).round) do |col|
(y-r).round.upto(y+r) do |row|
if (col-x)**2+(row-y)**2 <= r**2
set_pixel col, row, fill_char
end
end # row
end # col
end # def
end
canvas= Canvas.new do |c|
%w[! . + * X 0 = / \\ - |].each do |char|
c.draw_circle rand(70), rand(30), 4+rand(10), char
end
end
puts canvas
__________________________________________________________
Sent from Yahoo! Mail.
A Smarter Email http://uk.docs.yahoo.com/nowyoucan.html
> I would like to save a file with ruby using API32 with "dialog box save"
> to choose the filename and the directory, I have no idea to code this,
> someone can help me
> Thank you
you'll need a GUI application for Ruby.
There are many ... see here: http://www.trug.ca/Ruby_GUI_Toolkits
In addition to the list given there, there are some that use Java via JRuby ..
make a Google search for Monkeybars, Profligacy, Cheri.
I like Shoes most at the moment:
you get some example code for your problem right on this page:
http://blog.viamentis.com/articles/2008/04/04/shoes-a-ruby-gui-toolkit/
Best regards,
Axel
--
Psssst! Schon vom neuen GMX MultiMessenger gehört?
Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger
If you know how to do it in C/C++ using the Windows API, then you can
very easily do it in Ruby on Windows using the Win32API. There's a
getting started in the Pickaxe book
(http://whytheluckystiff.net/ruby/pickaxe/html/win32.html) - but this
is really just a primer. Once you've got your head around the
bindings, the real documentation is, of course, in the Windows API
itself, which is all available on msdn.com.
If you're not familiar with Windows programming in general, then, as
Axel said, you're better off using an easier GUI toolkit, which will
handle the Windows API stuff for you.
--
JJ
In Monkeybars, the picture/text field grouping would be handled by its
own model, view, and controller. This is how you'd tie that in:
class MainView < ApplicationView
# nesting defines how the component will be added or removed when
add_nested_controller or
# remove_nested_controller is called. This nesting is one of the
simpler ones that just drops in the
# component as is. There are more complicated variations that allow
you to write all code you want to
# determine layout specific arguments, positioning, and layout
validation.
nest :sub_view => :image_name, :view => :image_name_panel
end
class MainController < ApplicationController
def load
@text_image_controller = TextImageController.create_instance
# this will kick off the nesting for any nesting with a sub_view
of :image_name
add_nested_controller :image_name, @text_image_controller
end
end
2. A component built 'from scratch' atop a canvas, that is, handling
its own drawing and event management
Since we're using Swing, one could override the paintComponent method
on the Swing component used in the view. We've done some of this to
render real-time animated graphs with peak bars and graph transitions.
We even have it so each graph bar has it's own tooltip text.
Here's your example: A speedometer-type dial with a configurable range
and tick interval
In this case, I'd write my own view component by hand (typically we
use a designer for it).
A speedometer could be made by using some of the Java2D stuff out
there during paintComponent. The needle could be drawn with simple
line methods where you specify start and end coordinates. The ticks
could be drawn similarly as partial lines. I'd imagine some trig would
be involved in the calculations. I would also check to see if any Java
folks had already done this, as Java/Swing have been around for a long
time.
3. A component combining a canvas and existing widgets
I'd want to make the painted canvas widget into a nested controller,
so my canvas wouldn't have to care about stomping on other components
when it redraws itself.
For your example: A box that holds a component and paints a customised
border around it
This is actually pretty simple in Monkeybars. You can just set the
boarder of many (if not all) Swing components. We have a live example
using this that you can run via Java Web Start here:
http://www.happycamperstudios.com/monkeybars/twit/Twit-and-Twitter.jnlp
Here's the snippet that makes the drop-shadow border happen:
@image = Java::javax.swing.JLabel.new
@image.border = Java::org.jdesktop.swingx.border.DropShadowBorder.new
The drop shadow comes from the SwingX library.
I'd also like to note that example won us the GUI part of the script
bowl competition at Java One (us being JRuby).
4. A container that takes a collection of widgets and lays them out
according to some userdefined algorithm
There's a ton of ways to do this using Swing using Layouts.
Your example: A pure-ruby implementation of a wrapbox
(http://zem.novylen.net/ruby/wrapboxdemo.png)
This works out of the box just by using a FlowLayout in your
container. That can be as simple as this:
@main_view_component.layout = Java::javax::swing::FlowLayout.new
Some other stuff:
Monkeybars has a lot of options for configuring view mappings. View
mappings define how data moves from your model to the components in
your view, as well as how your components' data moves into your model.
One thing that was really important to us in Monkeybars was that for
moderate to large projects, a large update method in a controller that
intimately knew about the components used made testing incredibly
painful. We designed Monkeybars such that most communication between
the view and controller is done through the model via the mappings
mentioned above. Controllers may also send signals to the view for
lightweight or secondary renderings. There is no direct communication,
however. This makes testing super easy.
You _could_ write Java if you wanted, but we haven't run into
occurrences where Java (the language) is needed. You could write all
of your designs by hand in Ruby, which is fine. My preferred approach
is to use a designer tool, such as Netbeans.
Do you really want to lay something like this out by hand?
http://www.happycamperstudios.com/monkeybars/charlotte%20interface.png
Swing is a part of Monkeybars. We provide some simplified ways to
communicate with it (such as implicit event handlers). However,
Monkeybars doesn't shield you from Swing. This is both a pro and a
con. Swing is a powerful library, but it also has a lot of quirks.
Thanks to the folks at JRuby, we have Rubyized methods to all of our
Java proxies, and some nice implicit type conversions that make
integrating with Java look fairly natural. Monkeybars just makes Swing
more palatable, and provides a nice quarantine zone to place all of
your Swing code (in the view).
You're in JRuby, and that means you're in Java. Java buys you a built-
in JIT engine. JRuby's team has told everyone to flag occurrences
where MRI is faster as bugs. You also can run your code on any machine
with Java installed, and it's hard to find machines without Java.
Monkeybars itself is just a jar that happens to be a library. No Ruby
installation is needed! Leveraging Rawr you can also wrap your jars
in .exes or .app files. You can even use Java Web Start to hand
someone a link and the app will auto-install/update and run. You could
also integrate Monkeybars into your existing Java app, and start
writing all of your new code in Ruby. Java also has a lot of mature
code out there, as it has been around for a long time. One personal
experience I had was using SNMP. Ruby's SNMP library is great for
getting you started, but falls apart when you need to use the more
secure SNMPv3. SNMP4J has been around for a while, and is still active.
I know a lot of the Ruby community has some bitterness towards Java,
but this isn't Java the language we're using here, it's Java the
platform. I encourage anyone interested in GUI development to take a
peak at our examples and screencasts:
http://monkeybars.rubyforge.org/
http://monkeybars.rubyforge.org/tutorials.html
-Logan
I dont think there is any bitterness. Just when you use ruby for long
you will feel that Java is more verbose, and less flexible. Other than
that, I dont think there is any real "bitterness" or similar.
Realistically I think Ruby should rather be compared to i.e. perl, php,
python.
The static languages (Java C C++ C# D) out there are always much more
verbose compared to ruby.
D actually does a pretty good job of supplying "high level" features
like rich datatypes with literal constructors and full fledged lexical
closures. Those two can add up to a huge verbosity reduction.
martin
Thanks for the examples - Monkeybars looks pretty cool.
> 4. A container that takes a collection of widgets and lays them out
> according to some userdefined algorithm
> There's a ton of ways to do this using Swing using Layouts.
> Your example: A pure-ruby implementation of a wrapbox
> (http://zem.novylen.net/ruby/wrapboxdemo.png)
> This works out of the box just by using a FlowLayout in your container. That
> can be as simple as this:
> @main_view_component.layout = Java::javax::swing::FlowLayout.new
Yes, but my point was, can you define your own Layout in ruby?
> You _could_ write Java if you wanted, but we haven't run into occurrences
> where Java (the language) is needed. You could write all of your designs by
> hand in Ruby, which is fine. My preferred approach is to use a designer
> tool, such as Netbeans.
> Do you really want to lay something like this out by hand?
> http://www.happycamperstudios.com/monkeybars/charlotte%20interface.png
Actually, I do :) My preferred approach is to build widgets from the
bottom up, so that if I want to experiment with the layout later I can
do it easily in the code. Does netbeans use the "interface definition
file" approach or does it generate actual code from your UI?
> You're in JRuby, and that means you're in Java. Java buys you a built-in JIT
> engine. JRuby's team has told everyone to flag occurrences where MRI is
> faster as bugs. You also can run your code on any machine with Java
> installed, and it's hard to find machines without Java. Monkeybars itself is
> just a jar that happens to be a library. No Ruby installation is needed!
> Leveraging Rawr you can also wrap your jars in .exes or .app files.
This is indeed a huge plus.
> I know a lot of the Ruby community has some bitterness towards Java, but
> this isn't Java the language we're using here, it's Java the platform. I
> encourage anyone interested in GUI development to take a peak at our
> examples and screencasts:
No real bitterness - it's just a language I'd prefer not to use. The
JVM itself I'm all for.
martin
Martin DeMello wrote:
>
> Yes, but my point was, can you define your own Layout in ruby?
>
Yes you can define a new Swing layout manager with 100% Ruby code, just as
you can do most anything doable in Java from JRuby. I would say though,
that is is highly unlikely that you would need to do so. There are a great
variety of layout managers and most are pretty sophisticated, I surely
wouldn't take on writing a non-trivial one myself. If you are looking for a
very flexible layout manager designed for people doing layouts by hand I'd
suggest the MiG layout manager (http://www.miglayout.com/). You can see the
author's presentation at this year's Java One here:
http://developers.sun.com/learning/javaoneonline/2008/pdf/TS-4928.pdf
Martin DeMello wrote:
>
>> You _could_ write Java if you wanted, but we haven't run into occurrences
>> where Java (the language) is needed. You could write all of your designs
>> by
>> hand in Ruby, which is fine. My preferred approach is to use a designer
>> tool, such as Netbeans.
>> Do you really want to lay something like this out by hand?
>> http://www.happycamperstudios.com/monkeybars/charlotte%20interface.png
>
> Actually, I do :) My preferred approach is to build widgets from the
> bottom up, so that if I want to experiment with the layout later I can
> do it easily in the code. Does netbeans use the "interface definition
> file" approach or does it generate actual code from your UI?
>
Netbeans generates straight Java code, which you normally would never need
to touch. As for building a widget from the "bottom up" do you have any
examples? I've built several "widgets" using the graphical deisgner. In
Swing they tend to be JPanel + some components + logic (the logic of course
would all be in Ruby) which makes the visual designer even more useful. If
you're doing a super custom component involving doing your own drawing, that
is accomplished easily enough in straight Ruby code. In either of these
situations I fail to see how having a visual designer in any way slows you
down.
David
--
View this message in context: http://www.nabble.com/Can-your-GUI-framework-do-this--tp17714310p18146336.html
Sent from the ruby-talk mailing list archive at Nabble.com.
http://www.ruby-doc.org/docs/ProgrammingRuby/html/web.html
Then when you find it's too slow, look at fastcgi/fcgi/scgi - or reorganise
your app so that it runs as a standalone HTTP server, and proxy HTTP
requests to it from your front-end webserver.
Then you're not looking in the right text books. See for example the classic
Sedgewick "Algorithms" book.
The following reading may be useful:
http://en.wikipedia.org/wiki/2-3-4_tree
http://en.wikipedia.org/wiki/B-tree
http://www.catb.org/~esr/faqs/smart-questions.html#homework
Yes, it's possible, but you may find it less mind-bending just to use two
regular expressions:
puts "match" if foo =~ /\A[a-z]{3}\d{3}[a-z]{3}\z/ && foo !~ /\A...123/
If you really want a single regexp, then you can explicitly code a match for
the allowed digit ranges:
re = %r{\A [a-z]{3}
([02-9]\d\d | 1[013-9]\d | 12[0124-9])
[a-z]{3} \z}x
Or you can be clever and use a negative look-ahead assertion:
re = %r{\A [a-z]{3} (?!123) \d{3} [a-z]{3} \z}x
Note that %r{...}x is just a way to write regexps with embedded spaces and
newlines, so that they can be more easily understood.
HTH,
Brian.
Scroll down to "Why does the client run 'DRb.start_service'?" and read from
there.
That won't do anything as written; the two 'box' local variables are
distinct.
I'm guessing you mean something like this:
class ErrorBox
def initialize(box)
@box = box
end
def draw
@box.draw
end
end
eb = ErrorBox.new(Box.new)
eb.draw
This is a simple example of the "delegator pattern": (an instance of)
ErrorBox "has a" Box.
Over time I've found myself drawn more and more towards this pattern, and
use class inheritance less and less.
For me, the biggest advantage is that you can implement composite behaviour
easily. That is, your ErrorBox can contain multiple objects, either creating
them itself or having them passed in. Its own method 'x' can in turn call
A#y and B#z as appropriate. Composing systems in this way can make it much
clearer what each piece is responsible for.
It allows cleaner decoupling: for example, the 'foo' method of Box may not
make any sense when inside an ErrorBox, so you don't delegate it.
Unit testing with mock objects is easy. Your ErrorBox object can have a mock
Box, and you can easily check that it calls the correct methods on Box. With
inheritance you'd end up stubbing or mocking methods on the same object,
which can get messy. Tests are also more robust because they don't depend on
implementation details of Box.
Finally, there's more potential for code re-use. One ErrorBox object may
contain a TclBox, whilst another ErrorBox object may contain a QtBox. As
long as they have the same duck-type (e.g. in the above example they both
respond usefully to "draw") then they'll both work, without code changes,
whereas an ErrorBox which inherits from TclBox will only work with that. The
decision as to which to use can even be left until runtime.
Does that answer your question?
Regards,
Brian.
Yes, clearly there *is* a solution.
However your question fails to be "smart" on a number of counts. By omitting
critical details (e.g. what sort of table? in a database or an array? what
sort of database?) then nobody can give you a specific answer. Also, you
haven't given any indication of which avenues you've already explored, or
indeed of having made any effort at all on your own behalf to try to solve
the problem before posting. Maybe you have, but the important thing is you
haven't *shown* that you have. So why do you expect someone on the list to
take more effort in replying than you did yourself in posting?
To illustrate this, let me try making up a question or two which you could
have asked instead. These may or may not be anything like the actual problem
you have.
"I have a table 'documents' stored in a MySQL database that I'm accessing
using ActiveRecord. I'd like to be able to pick 6 rows from that table at
random. I can read all the rows into an array using Document.find(:all), but
I haven't been able to find a function in Ruby to pick a random element.
Could someone suggest where I should look? Thanks, Pragash"
In this case, someone might point you to the Kernel#rand method, and/or to
the many Ruby documentation sources.
However, your problem could be completely different:
"I have a table 'documents' stored in a MySQL database that I'm accessing
using ActiveRecord. I'd like to be able to pick 6 rows from that table at
random. I thought about reading the entire table into an array using
Document.find(:all), and then using rand(N) to pick elements from it, but
unfortunately the table has over 1 million rows and is too large to be read
into RAM. There are many gaps in the 'id' sequence column, so I can't do
Document.find(rand(N)+1) either.
Could someone suggest an efficient way to do this? Thanks, Pragash"
This question is completely different. It's not about Ruby but about MySQL,
since really you want to know if there's a SQL statement which can ask MySQL
to retrieve rows at random. You may find someone on this list who knows the
answer, or you may be referred to a MySQL mailing list.
To get more chance of a useful response you should also post relevant
details of your environment (which operating system and version; which
versions of Ruby, MySQL and ActiveRecord you're using), samples of code
you've run, and the errors you got back, copied and pasted verbatim.
The following document gives lots of really good, practical advice on asking
questions to a mailing list in a way which elicits the most useful response:
http://www.catb.org/~esr/faqs/smart-questions.html
I strongly suggest you read it.
Regards,
Brian.
As to the question itself, each client server application seems to
implement SQL standards in a non standard way. That is to say that
there is always some proprietary bit here or there. The SQL in oracle
might be:
select * from mytable where rownum = 123
and have the ruby random number generator insert a random value.
2008/7/7 <b.ca...@pobox.com>:
> box ||= Box.new
>> class ErrorBox
>> def initialize(box)
>> end
>> end
>>
>
> That won't do anything as written; the two 'box' local variables are
> distinct.
> I'm guessing you mean something like this:
> class ErrorBox
> def initialize(box)
> @box = box
> end
> def draw
> @box.draw
> end
> end
> eb = ErrorBox.new(Box.new)
> eb.draw
If ErrorBox really is a more specialized kind of Box, then subclassing makes
sense in terms of design. If it's not really a new kind of Box but wants to
use some of Box's behaviour then use delegation or consider mixins. Reg
Braithewaite has a decent article on this topic:
http://weblog.raganwald.com/2008/04/is-strictly-equivalent-to.html
Also, seek out the decorator in a book on design patterns. It's usually
presented as a way of extending the behaviour of objects in many orthogonal
ways in situations where subclassing would result in combinatorial
explosions of new subclasses. This is another case where mixins can also
make sense.
I have used this differently and found that it is not exactly as I said.
The rownum column in oracle exists only in a result set so it will work
for row 1 but no other UNLESS...
try this: (I am not at a system with oracle but I want to send this
before I forget.)
select * from
(select * from mytable) -- gets it all
where rownum = 123
This way, it has a full result set from which to select. Rather clunky
but I only looked at this between meetings.
That definitely isn't XMLRPC. The XMLRPC spec is very simple, see
http://www.xmlrpc.com/spec
Since the root element isn't <methodCall> then it isn't XMLRPC, so you won't
be able to use an xmlrpc client library.
What you seem to have is an ad-hoc XML-over-TCP exchange. So you need to:
(1) Open a TCPSocket to connect to the server
(2) Squirt your XML request down it
(3) Perhaps: half-close the connection (*)
(4) Read the response
(5) Either wait for the connection to close, or wait for the closing tag
of the response (**)
(*) This depends on how the server detects the end of the request - does it
look for the closing tag, or does it wait for the connection to close?
(**) The first case lets you read a blob and parse it afterwards. The second
requires you to parse as you read, e.g. with a stream parser.
If the server side closes the connection after sending the response, you
might be able to start with something as simple as
require 'socket'
conn = TCPSocket.new('1.2.3.4', 1234) # Destination hostname and port
conn.puts "<ping></ping>"
#conn.close_write # maybe not needed
res = conn.read
conn.close
puts res
Then pass res to a parser like REXML. If not, then you should pass the open
conn object to something like an REXML StreamParser to read element at a
time.
You'll just have to play with it to make it work, or talk to the server
designer, since there are some unknowns in the above. If they were using
XML-over-HTTP then it would be clearer, because the semantics of
end-of-request and end-of-response for HTTP are well-defined.
HTH,
Brian.
>> Just make test pass....
>
>According to my watch, you're about 24 hours too early.
>
Already the punch line is told before
---> On 2008/07/13, at 9:56, ru...@alef1.org wrote:
so, my source code, putting here(below) is no spoiling?
With the source, I'm in troubled of Syntax Errors.
the code is of C-language-thinking of mine,
and casting problems about…
Char|Symbol, String, Array or REGEXP-escape,
and Scope of variables
It maybe another Quiz…
-----source follows-----
#!/usr/bin/env ruby -Ku
#Oh, by the way... You may only use the characters `?`, `*`, `(`, `)`
and `-`.
#s
#Specifically, define a function `symbolify` that accepts an integer
#and returns a string composed of only the five characters shown above.
#The string, when evaluated, will equal the original number passed in.
def init
str = ':?:*:(:):-'
5.times { |i|
letters[i] = str[i]
}
end #init
def symb1(i)
s = ""
p = i / 5
# p = (i.abs) / 5
unless p < 1
symb1(p)
end
q = i.mod(5)
s += letters(q)
end
def symbolify(i)
letters = []
init
puts i
symb1(i)
# symb2(i)
end
puts symbolify(ARGV[1].to_i)
=== end of source ===
=============================
I've 3 bits, from time to time
Shindo Motoakira
<moto...@mac.com>
=============================
On 2008/07/14, at 4:50, Matthew Moss wrote:
> it doesn't quite work.
Yes(no?) it's not only out of work but
also off-track to the context of the quiz,
I'm realizing.
I'd well review solutions of others and regenerate mine
(^_^;) -- smile with sweats --
>http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/
>and another
>http://www.itk.org/HTML/WatershedSegmentationExample.html
>i've used bot a lot, shelling out to ruby mostly, unfortunately
>require hacking in c--. insight has ruby bindings though (via swig).
Dear Ara,
I couldn't find the Ruby bindings to Insight ... can't you point me somwhere ?
Thank you very much,
Axel
--
GMX startet ShortView.de. Hier findest Du Leute mit Deinen Interessen!
Jetzt dabei sein: http://www.shortview.de/wasistshortview.php?mc=sv_ext_mf@gmx
[snip]
I spent a good bit of time the other day downloading some of this
"literature". From a theoretical computer science perspective, it can
be shown that all garbage collection schemes are equivalent in a broad
sense. And when you benchmark them, all of them have strengths and
weaknesses that are workload-dependent.
And IIRC the first Lisp garbage collector was pure mark-and-sweep. I
forget where reference counting was first used -- maybe Snobol. And
stop-and-copy was also developed very early, maybe for Scheme. All
three of them are quite simple to understand, once you've bitten the
bullet and learned recursion. :)
> This is somewhat confusing for me, because it seems that using a
> mark and sweep generational style GC slows down Ruby, as per
>
> Matz's observations: http://www.ruby-forum.com/topic/123747
At a higher level, if you are doing a lot of garbage collection, you
need to look at your algorithms. And you need to supply a large enough
working set of real memory before you go finger-pointing at the
garbage collector, regardless of its type. There are some pretty good
web sites out there that have, via profiling, made some tremendous
improvements in Rails performance this way.
> I suppose I'm just naive, but it doesn't seem clear to me which is
> the 'best' GC style, from the above observations. There appears to
> be no clear answer.
That's because it's workload-dependent. What's worse, overall
performance on "modern" architectures is highly dependent on spatial
and temporal locality in your interpreter, whether it's method
dispatch, garbage collection, regular expression processing, bignum
operations, etc. It's not just garbage collection by any stretch of
the imagination. That's why I profile Ruby interpreters. :)
--
M. Edward (Ed) Borasky
http://pdxfoscon.org/start/
http://ruby-perspectives.blogspot.com/
"A mathematician is a machine for turning coffee into theorems." --
Alfréd Rényi via Paul Erd?s
M. Edward (Ed) Borasky <zn...@cesmail.net>
On Saturday 26 July 2008 20:43:37 Steven Parkes wrote:
> > From: David Masover [mailto:ni...@slaphack.com]
>
> > Keep in mind, I don't care about implementation at this
> > point, but design.
>
> Well, we're together on that, though, of course, peoples' opinion of design
> differs.
That's part of why I posted. (The other reason is to try to figure out the
exception handling.)
> > > release( s ).push(1,2,3,4,5) => nil
> >
> > What does "release" do, in this context? And why not make it
> > a method on the
> > wrapped object?
>
[snip]
> I didn't make it a method because I didn't want it to always have to be
> there, i.e., I wanted to be able to use
> s.push in the simple case (as opposed to s.sync.push and s.async.push).
I was thinking it would be easier to be able to do s.sync.push (or
s.async.push), and still have the semantics you want, as in:
released_s = s.release
released_s.push(...)
In fact, that's part of where my syntax came from -- the object returned from
every method call is a "ReturnPath" object, which can then be used to control
what happens after the call. That's why I have things like this:
s.length.now
What I'm thinking now is that I should be returning futures instead, so that I
keep the asynchronous-by-default behavior, but no extra effort is needed to
use things synchronously.
The one danger here is (again) exception handling. If something goes wrong, I
don't know when I actually make the method call, I know when I check the
future -- and one of the appeals of the design is that if I don't check the
future, it's a blind call.
> With that constraint, I didn't want to make it a method because it impinges
> on the namespace of the serial behavior of the actor, i.e., if sync is the
> default, and you have to say s.async to get async, you can't (easily) use an
> #async method on the actor itself.
Very early on, I realized I was going to end up doing this. I'd much rather
pollute the actor's namespace than the kernel namespace, and there are two
assumptions being made here: First, that most actors will be specifically
written for that purpose, and second, that there would be some sort of
standard override -- some #actor_send method.
So far, though, I haven't actually modified the real objects, only the proxy.
> > I would much rather use GC, if it would work. I'm not sure
> > how to make GC work
> > here, though -- and certainly not for one thread/actor.
>
> Yeah: you could have a problem with the thread-per-actor because it might
> not be clear when the actor is not actually doing anything (it can't be GC'd
> while its doing something)?
Well, I would love for Ruby to GC them on their own.
> > I do want to know how "async by default" was painful, though.
[snip]
> I really want code that looks serial to do the right serial thing, even if
> the objects are actors. So far, this works in dramatis.
I agree.
But I also want parallel code to not only be easy to write, I want it to be as
natural as serial code.
> Brings up selective receive again, though. Can the calling actor receive any
> other messages while it's waiting for #now?
In short, no. The implementation is absurdly simple -- I believe it's
something like 100 lines of code and 200 lines of specs.
So, that said, here's some relevant code:
class Suit
def initialize obj
...
@thread = Thread.new do
loop do
message = queue.pop
break if message.nil?
message.call object
end
end
end
The messages sent are actually blocks. Specifically:
def thread_eval &block
queue << block
end
And, predictably, the main usage is:
def method_missing *arguments, &block
ReturnPath.new.tap do |path|
thread_eval do |obj|
path.value = obj.public_send(*arguments, &block)
end
end
end
So, in short, nothing can happen in that thread outside the loop. The loop
will block calling that method on the object (indirectly). So if the method
itself ever blocks, the entire thread is blocked.
Messages can be sent while this happens, but they will be queued.
This was, in fact, the whole point -- from beginning to end of the method
call, nothing else may interfere. Within the object itself, there is no
concurrency, and you don't have to think about concurrency.
> But this introduces a big difference between serial and actor code even in
> the rpc case, which I don't like.
[snip]
> I> In single-threaded code, it's easy -- it's up to the caller.
>
> Right. There's no ambiguity. No choice. Here there's a choice. As soon as
> you have multiple actors, you have multiple stacks and in theory you can
> send the exception up either. I have cases where both are useful but I don't
> have anyway of making the runtime figure out the right way to handle things
> except making it explicit.
I see it as more a semantic problem -- I started this because I like working
with sequential Ruby, and I want to keep most of the semantics of that. But
concurrency does require at least thinking in a different way...
> > And how are we catching this, then? A method, maybe -- something like
> > linked_process_died?
>
> Something similar to that. More likely I'll provide a method that takes a
> block: if you want to catch an exception signal (using Erlang terminology),
> the actor calls this method with the block that it wants to get the signal.
> That block will be called when the signal is received, in which case the
> recipient won't be killed. This is more or less what Erlang does (I forget
> the BIF you call to do this.)
I can see that -- one advantage is, no pollution of the actor's own namespace.
In what context would it run?
> This is getting pretty deep into the guts. I started a list a few weeks ago
> for people discussing actor issues across languages/implementations:
> http://groups.google.com/group/actor-talk. Would it make more sense to do
> this there? There's also a list for dramatis
> (http://groups.google.com/group/dramatis) but if you just want to compare,
> actor-talk is probably better.
I want to compare, at first, and learn. Dramatis looks more complete, but I
like my syntax better (hey, I'm biased) -- ultimately, I'd rather not have
duplicate code. (Unless I dig deeper and find myself hating yours, in which
case, it's on! :P)
I am specifically interested in doing this in Ruby, so I don't think it's
entirely offtopic for ruby-talk, either.
>Maybe because active ftp and your firewall, try:
>require 'open-uri'
>open("ftp://whatever.ftp.site", :ftp_active_mode => false).read
I get TypeError: Cannot convert Hash into String.
--
My own blog (in polish) :
wujciol.yoyo.pl
Hi,
You can get it using ENV. Try this in irb:
ENV #hash with many info
Home folder: ENV["HOME"] #only path to home folder
Or if you want to try something else, also look using the Aptana Studio or the related plugins for Eclipse. That includes all of the functionality formerly captured by "Rad Rails"
Regards,
Andrew P. Tasi
Exceed Education
www.exceededucation.com
----- Original Message ----
From: Mayuresh Kathe <kathe.m...@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>
Sent: Friday, August 8, 2008 12:00:54 AM
Subject: Ruby IDE
Hello,
Is there a good IDE for Ruby?
At the moment am using "vi", plan to migrate to TextEditor under GNOME
I tried downloading ruby-ide from http://www.ruby-ide.com/
But it kept making me go round and round to get a trial version.
Best Regards,
~Mayuresh
> tag1.rb:6: undefined method `xpath' for nil:NilClass (NoMethodError)
>Do you see the nil in that line? Where is the nil coming from? Is the method
>before the .xpath, on line 6, possibly returning a nil and not an Elem?
>After pondering that, switch '#header' to '.header'!
Hi Phlip,
Thank you for your dot!!!
I follow your suggestion and change to '.header' or ".header" instead of "#header" and and it works. Ruby returns the tag's path like this: /tag1/tag2/div. But I see nowhere in the document about using "." and "#" in xpath() or css_path(). Do I miss something in the docucment?
Li
> I follow your suggestion and change to '.header' or ".header" instead of "#header" and and it works. Ruby returns the tag's path like this: /tag1/tag2/div. But I see nowhere in the document about using "." and "#" in xpath() or css_path(). Do I miss something in the docucment?
That's just the thing. I studied the crap out of HTML, XHTML, and light CSS, and
never learned until encountering assert_select that CSS has its own query
notation. Others with different career paths have learned nothing but - and they
all assume you know the same things.
Hpricot can handle _light_ XPath, and can handle various CSS Selector notations.
The documenters have all assumed that someone else taught you how they work. So
google for "CSS Selector", without x-ref'ing Hpricot!
--
Phlip
That doesn't make sense. response.upcase is always true (not nil or false),
so (response.upcase and "BYE") is just the same as "BYE". Try it in irb to
convince yourself.
There's also no need to initialise response at the start of the program.
Apart from that your code looks fine. Here is an alternative version, using
regular expressions and 'next' and 'break' flow control.
puts "Hey Sonny! It's your lovely Grandmother! How are yeah?"
bye = 0
while response = gets
case response
when /^BYE$/
bye += 1
break if bye >= 3
puts "Hmmm... I would prefer..."
next
when /[a-z]/
puts "Huh?! I CAN'T HEAR YOU!"
when /[A-Z]/
puts "NO! NOT SINCE #{1930+rand(21)}!"
end
bye = 0
end
(The original problem didn't say what to do if you said a blank line to
Granny, or a line which contained no alphabetic characters. In this program
she just ignores you, but still resets the bye counter to zero. This is easy
to change.)
Note there is a subtlety with "gets". If you ever modify this program to
take arguments on the command line, "gets" will behave strangely, because it
will treat the command line arguments as filenames to read. For example,
ruby granny.rb 1930 1950
will try to read responses from files called "1930" and "1950", instead of
from stdin. To make sure you're always using stdin, you're better off
writing
while response = $stdin.gets
(This magic Kernel#gets is a bit of ugliness inherited from Perl. Personally
I find it trips me up rather than being helpful, which is why I mention it
here :-)
Regards,
Brian.
P.S. At some point you may wish to rewrite this code in a way which can
easily be unit-tested - and which lets you talk to multiple grannies at the
same time :-)
You're probably thinking of Kernel.select. To poll if data is available for
read on IO object foo, and read as much data is available, up to 1024 bytes
max:
if select([foo], nil, nil, 0)
res = foo.readpartial(1024)
end
(select also returns true if the file is closed, in which case read will
return nil)
Beware of race conditions in your code - i.e. the child might not generate
output on stderr until some time later, so you may need to continue to poll
periodically.
That's one of the joyful aspects of Ruby, especially coming from Perl (am I
passing a scalar? A reference to an array or hash? A filehandle? A typeglob?
Argh!)
Similarly from C++ (am I passing a value? A pointer? A reference?!)
> I want to pass the array to a function. This function will take the
> array, make a new copy so as to protect the original from any changes.
> Changes will be made to the copy and then the copy is returned.
>
> How do i do that?
>
> Ive looked dup but i dont think it works for objects
Everything's an object in Ruby. The only things you can't dup are certain
immutable primitive objects (e.g. nil.dup, 3.dup, :foo.dup), and they don't
need to be dup'd anyway.
If you dup an Array you will get a new array, but all the slots in that
array will point to the same objects as the slots in the old array. This
causes aliasing:
irb(main):001:0> a = ["foo","bar"]
=> ["foo", "bar"]
irb(main):002:0> b = a.dup
=> ["foo", "bar"]
irb(main):003:0> b[0] = "baz"
=> "baz"
irb(main):004:0> b
=> ["baz", "bar"]
irb(main):005:0> a
=> ["foo", "bar"]
irb(main):006:0> b[1] << "xxx"
=> "barxxx"
irb(main):007:0> b
=> ["baz", "barxxx"]
irb(main):008:0> a
=> ["foo", "barxxx"]
irb(main):009:0>
So maybe what you're thinking of is a "deep copy", which recursively
duplicates the object and all the other objects refered to therein
(remembering that they may refer to each other in a circular fashion).
The easiest way to do this is to Marshal the graph of objects into a string,
and create a new graph of objects from that string.
irb(main):009:0> a = ["foo", "bar"]
=> ["foo", "bar"]
irb(main):010:0> b = Marshal.load(Marshal.dump(a))
=> ["foo", "bar"]
irb(main):011:0> b[1] << "xxx"
=> "barxxx"
irb(main):012:0> b
=> ["foo", "barxxx"]
irb(main):013:0> a
=> ["foo", "bar"]
irb(main):014:0>
In practice, few Ruby programs actually do this. It's much more common for
Ruby code to modify complex data structures in-place (*). If you come from a
functional programming background, you may find this distasteful :-)
OTOH, if you are enforcing a regime where individual objects cannot be
mutated, then you don't need a deep copy in the first place:
irb(main):014:0> a = ["foo", "bar"]
=> ["foo", "bar"]
irb(main):015:0> a.each { |e| e.freeze }
=> ["foo", "bar"]
irb(main):016:0> a.freeze
=> ["foo", "bar"]
irb(main):017:0> b = a.dup
=> ["foo", "bar"]
irb(main):018:0> b[0] = "baz"
=> "baz"
irb(main):019:0> b[1] << "xxx"
TypeError: can't modify frozen string
from (irb):19:in `<<'
from (irb):19
from :0
irb(main):020:0> b[1] = b[1] + "xxx"
=> "barxxx"
irb(main):021:0> b
=> ["baz", "barxxx"]
irb(main):022:0> a
=> ["foo", "bar"]
irb(main):023:0>
Usually you wouldn't go so far as to freeze all objects, as that's just a
pain, but you can have it implicit in your contract with the caller that you
promise not to modify any objects which are passed to you. In this case,
returning a new Array which points to (some of) the same objects as the old
Array is reasonable behaviour.
Usually what happens is that the caller forgets about the old Array, leaving
it to be garbage collected. Any objects which are referenced only by the old
Array are also garbage-collected at that time, but those referenced by the
new Array live on.
HTH,
Brian.
(*) Especially since some objects cannot be Marshalled, e.g. IO objects,
Proc objects.
Try: assert_in_delta(expected, somefunction(blahblah), 0.001)
(Two floats which look the same when printed may actually be slightly
different, due to the inexact nature of the internal representation)
Because it is defined in the specification for URLs that + means space.
If you want a real + in your URL, you have to escape it, e.g.
http://localhost/foo/science%2Bstudents
(the same applies to a number of other special characters too)
When generating links dynamically in a page for people to click on, you
should be escaping them in this way.
Regards,
Brian.
This works, though I had to add a sleep call to give it time to pick
up an error:
require 'open3'
require 'timeout'
program = File.join(Dir.pwd, "miniserver.rb")
cmd = "ruby #{program} &"
Open3.popen3(cmd) do |stdin, stdout, stderr|
sleep 0.1
if select([stderr], nil, nil, 0)
p stderr.readlines
end
end
puts "Done"
This approach actually makes me less comfortable than my original
approach, however, because now I'll have to worry that I didn't sleep
long enough and an error will go unnoticed.
Regards,
Dan
----- Original Message ----
From: Daniel Bush <dlb....@gmail.com>
To: ruby-talk ML <ruby...@ruby-lang.org>
Sent: Wednesday, August 20, 2008 2:55:07 PM
Subject: Re: ActiveRecord Question -- making arrays or hashs out of database tables
Glenn wrote:
>
> Better yet, I'd like to be able to create an array of hashes, where each
> element of the array is equal to a hash of the fields in the table, like
> this:
> [{:x => 1, :y => 'a', :z => 1.1}, {:x => 2, :y => 'b', :z => 6.2}, {:x
> => 3, :y => 'c', :z => 0.001}]
Yes, you can do that.
I have a 'clients' table which is represented by a 'Client' model (maybe
in a rails application).
I can do
clients=Client.find(:all).collect {|c| c.attributes }
and access it like
clients.each do |client|
client['first_name'] # do something with first_name field value
end
which gives you your array of hashes.
However,
clients=Client.find(:all)
will give you
clients.each do |client|
client.first_name
end
which is nicer and you get all the power of active record as a result,
because 'client' is an instance of Client and not just a hash.
> Can anyone tell me if this is doable in ActiveRecord, or in some other
> Ruby package, or with some stand-alone Ruby code?
Someone might shoot me down here, but I'd say that ActiveRecord is good
for working with small updates and selects as in the sort of thing you
might do with a web app interface.
If you're not using rails, then it is quite likely you might look at
alternatives. There are drivers for various databases which will fetch
data into arrays and hashes, and their are also alternatives to
activerecord which do ORM. Haven't been using a lot of them lately and
it may depend on the database.
Regards,
Daniel
I believe that x y z is parsed as x(y(z)):
irb(main):013:0> puts ArgumentError
ArgumentError
=> nil
irb(main):014:0> puts ArgumentError 123
(irb):14: warning: parenthesize argument(s) for future version
NoMethodError: undefined method `ArgumentError' for main:Object
from (irb):14
from :0
irb(main):015:0> puts ArgumentError(123)
NoMethodError: undefined method `ArgumentError' for main:Object
from (irb):15
from :0
irb(main):016:0>
and x y {block} is parsed as x(y() {block}), i.e. y is forced to be a method
call as that's the only meaningful thing next to a block.
irb(main):017:0> def Wibble(*args,&blk)
irb(main):018:1> puts "Args: #{args.inspect}"
irb(main):019:1> puts "With block" if blk
irb(main):020:1> end
=> nil
irb(main):021:0> puts Wibble { raise "hello" }
Args: []
With block
nil
=> nil
irb(main):022:0> puts Wibble Wibble { raise "hello" }
(irb):22: warning: parenthesize argument(s) for future version
Args: []
With block
Args: [nil]
nil
=> nil
There's also the ambiguity between hash literal and block to consider:
irb(main):027:0> puts { :one => 2 }
SyntaxError: compile error
(irb):27: parse error, unexpected tASSOC, expecting '}'
puts { :one => 2 }
^
from (irb):27
from :0
irb(main):028:0> puts({ :one => 2 })
one2
=> nil
irb(main):029:0> puts 123, { :one => 2 }
123
one2
=> nil
irb(main):030:0> puts { raise }
=> nil
irb(main):031:0> puts :one => 2
one2
=> nil
B.
Well, now that you explained it, it makes perfect sense! Thanks.
I guess in the future I'll double-check a little more carefully that my
code is doing what I expect when I leave out parens.
Doug
Roughly. The Array itself exists on the heap independently of a and b; a and
b are local variables, basically just slots in the stack which contain a
reference to the Array.
The difference is that local variables themselves are not objects, and you
cannot take a "reference" to a or b.
So whereas in C you could write
void *p = malloc(50);
void *q = p; # q is a another pointer to the malloc space
void **r = &p; # r points to the pointer p <<<< NOTE
in Ruby you can only do
p = "x" * 50
q = p
This actually makes life simpler. If you call
foo(p)
then the method foo can mutate the object p, but on return p will definitely
be unchanged, i.e. is a reference to the same object. You cannot change what
p references, unless you explicitly return a new object, e.g.
p = foo(p)
Of course, the biggest simplification over C is garbage collection. The
Array will be garbage collected once nothing else contains a reference to it
(either a local variable or another live object)
> a = b.dup
>
> create some NEW pointers but which point to the same memory space.
No. It allocates new memory space and copies the contents of the space
referenced by 'a' into the new space.
However, that space may in turn contain pointers (references) to other
memory spaces (objects). Since this is a direct copy, the new object
contains the same references as the old object.
obj1 = "foo"
obj2 = "bar"
a = [obj1, obj2] # a points to an Array which contains &obj1,&obj2
b = a.dup # b points to a different Array which contains
# &obj1, &obj2
In the latter case you could have written b = [a[0], a[1]], or
b = [obj1, obj2], and got the same result: a new array, which contains the
same pointers as the old array.
You can modify the array referenced by b - e.g. by adding or replacing an
element - and this won't affect the other array referenced by a. But if you
follow b[0] to find obj1, and modify obj1, then obj1 is changed.
Subsequently accessing the object referred to by a[0] or b[0] will find the
same changed obj1.
Use the "object_id" method to see if you're pointing to the same "memory
space".
irb(main):001:0> a = ["abc","def"]
=> ["abc", "def"]
irb(main):002:0> a.object_id
=> -605609816
irb(main):003:0> b = a.dup
=> ["abc", "def"]
irb(main):004:0> b.object_id
=> -605638770
You can think of object_id as a kind of encoded pointer.
HTH,
Brian.
True. But in Ruby you're not passing values by reference; you're passing
references by value!
Remember in C it's common to do
struct foo *bigthing = malloc(sizeof(struct foo));
From that point onwards, you pass around the pointer 'bigthing':
void print_foo(struct foo *t)
{
...
}
...
print_foo(bigthing);
Here you are passing a pointer by value. That's exactly what you're doing in
Ruby. The caller cannot modify the variable 'bigthing' so it points to
something else, but they could modify the structure which it points to. (*)
Think of Ruby objects as 'structs' if you like. K&R C didn't allow passing
structs by value at all. ANSI C does, but it's inefficient and usually
frowned upon:
void print_foo(struct foo t) /* could be a big stack frame! */
...
print_foo(*bigthing);
In any case, passing a struct by value will have the same problem you
describe, if it in turn contains pointers to other objects. e.g.
struct foo {
struct bar *header;
struct baz *footer;
}
Even if you pass bigthing (an instance of struct foo) by value, which means
that your 'header' and 'footer' pointers can't be changed, the header and
footer objects themselves can still be modified in-place.
> So switching to ruby where pass by reference is the only choice seems to
> be making my programming a little less smooth.
On the contrary - in Ruby where everything is a reference passed by value,
this choice no longer has to be made, and everything becomes wonderfully
regular.
> Im just used to knowing
> that the original value wont be changed.
Only in certain limited cases (i.e. passing simple integers, and structs
which contain nothing but integers). Most useful programs need data
structures which include pointers.
In any case, the same applies to Ruby numeric types, as they are immutable
objects.
def foo(my_int) # my_int is a local copy of the object reference
my_int = 4 # now my_int points to a different object
end
a = 1
foo(a)
puts a # a still contains 1 (i.e. a reference to the Fixnum object "1")
That is: you can't "change the number 1". You can only change a local
variable to reference a different number. And because references are copied
(passed by value), the caller is still referencing the original number.
When I first came across Ruby, things like this used to worry me (also
things like types and variable names not being checked at "compile" time).
My advice is: go with the flow. Try doing things differently. Then you may
find out that the benefits of doing it this way in practice outweigh the
risks you *perceive* initially when coming from a different way of thinking
and working.
If after trying it for real this still worries you, use Erlang :-)
HTH,
Brian.
(*) I'm ignoring the possibility of "const" declarations here. The same
limitations apply: even if you declare
void print_foo(const struct foo *t)
then this only protects you for one level. If *t contains pointers to other
objects, then you can't change the pointers, but you can change the things
pointed to.
In any case, all bets are off if the function you're calling uses casts.