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