Archive for May, 2007

How to do pythonic list comprehensions with conditions in ruby? | One Big Library.

How to do pythonic list comprehensions with conditions in ruby? | One Big Library.

Somone was discussing this, I thought I’d post some examples:

I see the selects being written there attempting to operate on the variable. If this does do anything, it will be in-place on the array (or range) that you’re operating on. For an array, this is not really a problem, other than you probably didn’t want to do that:
[source:ruby]
>> a = (’a’..’z').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
>> a.select do |l| l =~ /[aeiou]/ ? (l << ‘-mod’; l) : nil end
=> ["a-mod", "e-mod", "i-mod", "o-mod", "u-mod"]
>> a
=> ["a-mod", "b", "c", "d", "e-mod", "f", "g", "h", "i-mod", "j", "k", "l", "m", "n", "o-mod", "p", "q", "r", "s", "t", "u-mod", "v", "w", "x", "y", "z"]
[/source]
Obviously, you could make a copy of the array at this point, and it would solve the problem, at the obvious cost. See at the end for some examples of another way to achieve a similar effect in ‘one line’.

With a range, the outcome is different:
[source:ruby]
>> a = (’a’..’z')
=> “a”..”z”
>> a.select do |l| l =~ /[aeiou]/ ? (l << ‘-mod’; l) : nil end
=> ["a-mod"]
>> a
=> “a-mod”..”z”
[/source]
Why? because you’ve in-place modified the range. Now, what is an enumerator to do with a range, when you’ve modified it in-line? What is the next item from ‘a-mod’..’z’ from ‘a’?
‘a’ is no longer in the range.

If you want numeric iteration over a list, you first of all need a list!
[source:ruby]
>> r=[]; (’a’..’z').each {|v| r << v if v =~ /[aeiou]/}; r
=> ["a", "e", "i", "o", "u"]

>> y = []; for x in 0..10 do y << x * 3 if x % 2 == 0 end; y
=> [0, 6, 12, 18, 24, 30]
[/source]
The last ‘;var’ is only for irb to print the array we just created, you can remove it, or, if you really really want to, you could do this (might be suitable for a function)…
[source:ruby]
var = (y = []; for x in 0..10 do y << x * 3 if x % 2 == 0 end; y)
[/source]
There are some things in the ruby grammar I truly love, no matter how ‘useless’ they may seem.

None of this really offers you the pythonic syntax, but that’s not necessarily a bad thing.

The python syntax provides (in ruby terms) essentially two block passes. One before the for, and one after.

We can get closer to replicating this, but it still runs over the array twice (so the above solutions may be better), and the ordering of operation is different:
[source:ruby]
(0..10).select { |v| v % 2 == 0}.each {|v| v * 3}
[/source]

In comes inject…

[source:ruby]
>> (0..10).to_a.inject([]) do |a,x| a << x * 3 if x % 2 == 0; a end
=> [0, 6, 12, 18, 24, 30]
[/source]

djberg96: The Paradox of (Programming Language) Choice

djberg96: The Paradox of (Programming Language) Choice

Just keep the options down, and ensure as much compatibility as possible. Think of the Java VM and SDK options, people don’t complain too much about those differences because they don’t affect most code.

OpenDNS | Providing A Safer And Faster DNS (but lower accuracy!)

OpenDNS | Providing A Safer And Faster DNS

solsTiCe has joined #ruby-lang
solsTiCe: hi. a pb with http://ruby-lang.org/ ? i got "You don't have
       permission to access / on this server." !
solsTiCe: i am using opendns server
raggi: Name:    carbon.ruby-lang.org; Address:  221.186.184.68; Aliases:
       www.ruby-lang.org
solsTiCe: i got that with opendns www.ruby-lang.org       A
          208.69.32.132
solsTiCe: but i got that now
solsTiCe: host www.ruby-lang.org
solsTiCe: www.ruby-lang.org       CNAME   carbon.ruby-lang.org
solsTiCe: carbon.ruby-lang.org    A       221.186.184.68
raggi: the essence of why I think a service like OpenDNS is a bad idea.

The general idea of editing DNS query results on the fly really makes me itch. the idea sounds very dangerous, but some more digging points out that this can all be turned off on the service.

Competing On The Basis Of Speed - Google Video

Competing On The Basis Of Speed - Google Video

Very worth watching.

Calling Erlang from Ruby (Teaser)

So someone has come up with a solution for linking Erlang to ruby. This could be potentially useful.

The original article: Calling Erlang from Ruby (Teaser)

The library is called Rebar (Ruby to Erlang Bridge And Runner). Rebar has two parts: an Erlang server and a Ruby client. The server listens for JSON-RPC requests, calls the specified Erlang function, and responds with a JSON-RPC response. The Ruby client object simply accepts any method name, captures it with method_missing, wraps everything up in a JSON-RPC request, fires it off, waits for the response, and then extracts the result out of the JSON-RPC response, returning it like a normal Ruby call.

Unfortunately this means that you’re going to be waiting for both RPC, parsing, routing, and method_missing in ruby. Thus the ‘teaser’ I would say.

Erlang also has some powers of reflection though. A better solution for some applications would be to publish a dsl between them for the particular application. Maybe even a full object dsl. Depending on how much meta-information can be made available to each side, this direction may get faster.

I think the most reliable way would involve generating the protocol API for the RPC from ruby written generators. This should have the advantage of adding a fully ruby DSL. I’m starting to discuss a design that looks more like ruby2erlang now though. I guess maybe it’s not /that/ hard.

Anyway, this could solve a number of problems relatively trivially for scaling networked apps, with erlang handling buffering and non-blocking high concurrency jam, and ruby based ‘consumers’ (which it’s worth noting could live anywhere, which is not completely uncommon for such high load scenarios).

Anyway, this is really just another thing for my already very long list of ideas I’d like to give some attention :)

Readability?

[source:ruby]
def factorial n
fac = 1
1.upto n do |i|
fac *= i
end
fac
end

def factorial n
fac = 1
for i in 1..n do
fac = fac * i
end
fac
end

def factorial n
fac = 1
1.upto n { |i| fac *= i }
fac
end

(defun factorial (n)
(loop for i from 1 to n
for fac = 1 then (* fac i)
finally (return fac)))
[/source]

raggi » Ruby for Windows in Under 700 bytes (and executable!)

This was a little bit of random inspiration I got from this little javascript file which _why wrote:
Ruby for Windows in Under 1K.

I thought that was pretty cool… So I made it a bit cooler, and now propose some ideas I’ll be working on if I can find the time…

When I stumbled upon this stranded little baby bear in the woods I thought it looked kinda cute. Unfortunately this little bear had no real motivation to execute it’s cuddly little plans. Seeing him so close to growing into a strong beast which might aid my hunting, I felt compelled to provide him with a spice of one-step motivation (before I redirected his focus in order to utilise him for my own devious plans of forest domination).

So anyway, the result was a nasty little .bat file in 640 bytes, which simply echos try.js and calls it. This version also hard codes support for EOT to exit.

Opps, I winked.

Anyway… time for some real web page nastiness with a wide line of code:

[source:ruby]@echo tryurl=”http://tryruby.hobix.com/irb?cmd=”;w=WScript;o=w.StdOut;i=w.StdIn;function wget(url,hdrs){var http=w.CreateObject(”Microsoft.XMLHTTP”);http.open(”GET”,url,false);for(var k in hdrs)http.setRequestHeader(k,hdrs[k]);http.send(”");return http.responseText;}sess=wget(tryurl+escape(”!INIT!IRB!”),{});w.Echo(”Interactive Ruby ready. (send ^D to exit)”);o.Write(”>> “);i.Read(0);while(true){cmd=i.ReadLine();resp=”";ps=”>> “;if(cmd==”\004″)break;if(cmd){resp=wget(tryurl+escape(cmd).replace(/\+/g,’%%2B’),{’Cookie’: ‘_session_id=’+sess});ps=”..”;if(resp){o.Write(resp);ps=”>>”;}}o.Write(ps+” “);}>t.js
@cscript//Nologo t.js&del t.js[/source]
- That’s 640 Bytes, with some extra documentation and an extra char on the prompt! I’m sure it could be shorter, but I don’t care. That’s damn near half a kB, and the block size of most all devices is larger than that these days (devices like, don’t even think this small, dude).

And the tryruby.bat

Now, on to some not so original and dangerous thinking…

The tool as it stood in a .js file was a bit cumbersome. You’d have to load up a cmd, get into the right dir, and run cscript on it. Now, you can just carry this .bat round on a USB stick and get a ruby XML-RPC to …. the try ruby server …. ;-)

As another kinda funky side idea, you could carry your own one-time pad algorithm in another .bat based on this, processed via tryruby, along with a username and password to get into your own ruby processes.

It might be a crazy stupid idea, to some, but it’s also pretty damn useful. I mean, it’s a remote ruby shell, with NO dependencies except the OSes native scripting languages…. I don’t even necessarily need putty after this (no, I’m not entirely serious there, but not far off either).

As I say, I’ll be looking into this more if I get the time, as the ideas are very loose right now, however, I should imagine it won’t be too hard to attain some reasonable level of security. Together with a little DSL this could make a very neat (and immediately extensible over the wire) remote control or remote data recovery system, with no dependencies.

I’m sure it’s easy to make a similar thing for *nix, in fact, I have vague recollections of a .sh version of a similar tool lying around somewhere too.

So the plan:

  1. Look at tryruby, sandbox and whatever else may be relevant.
  2. Build in SSL support if it doesn’t work already.
  3. Build an authentication mechanism (maybe some crazy extras here)
  4. Load up a server somewhere safe (maybe, in it’s own xen vm :) )
  5. Give some of those goony linux sysadmins wet dreams

If I build it up to anything really useful, I’ll release it. I’m obviously concerned about security, but equally, in this case (or this direction of use) we’re intending to open a hole. I just want some strong authentication and traffic protection before I’d let anyone else ‘go wild’.

Does anyone use anything like this in ruby (considering how many of these kinds of things are out there)?

Maybe I’ll refactor this post to be more succinct or make more sense later. But for now, I don’t care. It’s a hack and I think it’s cool.

Keep up the good work _why.

Update: Found a bug in the code, pointed out from the original fix mentioned in comment 3. The string replace was actually not running across the whole string, even in _why original version. The the first argument to replace actually needs to be /\+/g rather than ‘+’.

Thanks to anyone who submits any more bug reports, as this really isn’t something I’m spending time on right now :D

Edit With… et al

Lives here:

HKEY_CLASSES_ROOT/*/shell/

enjoy.