Rails. Spidering. Python 2. Baubles in Orbit. Posted by Uncle Bob on 08/19/2008 I have put together a nice little demonstration of the Bauble concept. You may recall that I first wrote about it here . Baubles are a simple component scheme for Ruby, good for when you want a component, but don’t need something as heavy as a gem. orbit.zip contains all the files for this demonstration. I suggest you download and unpack it. First you need to install the Bauble gem. Don’t worry, it won’t hurt anything. Now you should be able to run the orbital simulator. Cd orbit/MultipleBodyOrbit/lib jruby multiple_body_orbit.rb A swing window should pop up and you should be able to watch an orbital simulation. The thing to note, if you are a ruby programmer, is the use of the term Bauble::use(-some_directory-) . If you look in either of the two Baubles, you’ll see that the require statements within them do not know (or care) about the directory they live in.
Take a look at the Bauble source code. Also take a look at the two baubles. Better Ruby Idioms. November 12th, 2009 Carl and I have been working on the plugins system over the past few days. As part of that process, we read through the Rails Plugin Guide. While reading through the guide, we noticed a number of idioms presented in the guide that are serious overkill for the task at hand. I don’t blame the author of the guide; the idioms presented are roughly the same that have been used since the early days of Rails. However, looking at them brought back memories of my early days using Rails, when the code made me feel as though Ruby was full of magic incantations and ceremony to accomplish relatively simple things.
Here’s an example: To begin with, the send is completely unneeded. This code intended to be used as follows: What the code does is: Register a hook so that when the module is included, the ClassMethods are extended onto the classIn that module, define a method that includes the InstanceMethodsSo that you can say acts_as_something in your code To be used via: A better solution: JRuby 1.1 Released. What is a ruby object? (introducing Memprof.dump) After Joe released memprof a few days ago, I started thinking about ways to add more functionality. The initial Memprof release only offered a simple stats api, inspired by the one in bleak_house: require 'memprof'Memprof.starto = Object.newMemprof.stats 1 test.rb:3:Object With the help of lloyd‘s excellent yajl json library, I’ve slowly been building a full-featured heap dumper: Memprof.dump. require 'memprof'Memprof.start[]Memprof.dump Where can I find it?
This new heap dumper will be in the next release of Memprof. What else is planned? Over the next few days, I’m going to add a Memprof.dump_all method to dump out the entire ruby heap. Why should I care? In building and testing Memprof.dump, I’ve learned a lot about different types of ruby objects. Objects and Floats o = Object.newo.instance_variable_set(:@pi, 3+0.14159) This ruby object points to its class (Object 0x1854b38) and has some instance variables- here, there’s only one variable named @pi that points to another object at 0x1823da0.
Infinite Ranges in Ruby. First let’s define an Infinity constant (since Ruby does not come with one): Now let’s see if we can create a Range Object with it: Okay, no errors. Now let’s try to use it: ( 1 ..Inf).include? ( 10000000 ) (-Inf.. 0 ).include? (- 1000 ) (-Inf..Inf).include? Now let’s try using it as a ‘lazy’ list: ( 1 ..Inf). each .take( 5 ).select { |v| v.even? ( 100 ..Inf).step( 100 ).take( 3 ) One last thing: ( 1 ..Inf). each { |v| puts v } ...etc (quite alot of numbers...) lazy evaluation? Some of the applications of Lazy Enumerators (discussed here: In particular, the lazy_select, and lazy_map family of functions defined in that article will also work fine with Infinite Ranges: Enumerator. new do |yielder| yielder. yield (obj) if yield (obj) ( 1 ..Inf).lazy_select { |v| v.even? This trick was discovered by Beoran in response to a question by FreakGuard in #ruby-lang on freenode. lazy_select by gfarfl.
Like this: Be the first to like this. Trackbacks. StackOverflow cool Ruby questions. I have participated heavily during the last 2 weeks in answering Ruby tagged questions on stackoverflow. That took place mainly after Ryan Bates tweet wishing to see more Ruby developers on stackoverflow. Since then I have enjoyed reading various kinds of questions that range in level from basic to professional ones and which cover various stuff like normal questions, tricks, meta programming, best practices and language specific features.
So, I’m announcing in this post an endless series called “Stackoverflow cool Ruby questions” which will target cool Ruby questions on stackoverflow. I strongly recommend that you visit Stackoverflow on daily basis and try to participate if you have the time, but if you don’t, then I hope that you will enjoy this educational series. There are currently more than 4,640 tagged Ruby questions, I’ll try to mix old + recent questions. Please don’t hesitate to give any notes regarding the idea and the way the questions are picked and presented. Into this? Eval() Isn't Quite Pure Evil. I was explaining method lookup to the Lone Star Ruby Conference attendees and needed to show some trivial code like this: module B def call puts "B" super end end module C def call puts "C" super end end module D def call puts "D" super end end Unfortunately, my space was limited due to the code being on slides and me needing to show more than just what you see above.
I cracked under the pressure and committed two major programming sins. First, I collapsed the code with eval() : %w[B C D].each do |name| eval <<-END_RUBY module #{name} def call puts "#{name}" super end end END_RUBY end Then I really blew it when I jokingly apologized to the audience for using eval() . I got the first email with corrected code before I even finished the speech. Only, his corrected code didn't quite work. %w[B C D].each do |name| mod = Module.new do define_method :call do puts name super() end end Object.const_set(name, mod) end Is that better? That leads us to the natural question: why is eval() pure evil? Avi Bryant on Trendly, Ruby, Smalltalk and Javascript.
2. So Dabble DB is written in Smalltalk? Yes. The core of Dabble DB is written in Smalltalk. We do use a bunch of Ruby scripts and actually a little bit of Python for a sort of infrastructure stuff, peripheral stuff, but the core is written in Smalltalk and runs on Seaside. 3. What's your new project? Is it a product yet? Trendly came out of something that we really needed internally for Dabble DB, which is that we use - like a lot of people do - Google Analytics to track our web traffic. I spent a while just reading about stats and we were searching this stuff to come up with a model that I thought would work for this kind of traffic. If your traffic just randomly goes up a bit, we don't want to tell you about that, but if you been slashdotted and suddenly you've got huge referrals from everywhere then that's something we wish to report. 4. 5.
Then Google Analytics basically gives us an API token and we can use that to do queries against your Google Analytics data. 6. Yes. 7. 8. 9. 10. Ruby One Niner. All my server’s Ruby applications, most notably my books site, have been running on 1.9.1 for over a month now. During the process of upgrading Ruby I jotted down a few notes on the process I followed, the problems I encountered and the ways in which I solved them. None of this is new information, but hopefully bringing these solutions together will be of use to those with similar setups, or at least to myself in the future. Installing Ruby I installed Ruby 1.9.1 on an Ubuntu 8.04 (LTS) server, which was reasonably simple in and of itself, although the Ruby ecosystem as a whole has clearly not quite caught up to the new VM.
Ruby 1.8.6 is still the default version of Ruby available on the Ubuntu package system, and while there is a version of Ruby 1.9 available, it’s quite out of date. Uninstalling Ruby 1.8.6—assuming it was installed with aptitude—is extremely simple: sudo aptitude remove ruby1.8 Installing gems Is it Ruby 1.9? Some gems just worked Mongrel MySQL Updating applications. Multiple Programming Language Implementations - This Annoys Me t. I've been reading books on Ruby. I want to know the language really well. I'm that kind of programmer. I love to know the exact details of a language as much as possible. By far the thing I like least about the Ruby language at this point is that it feels like two languages, Ruby 1.8.x and Ruby 1.9.x. Each time I read a paragraph that explains a difference between Ruby 1.8 and Ruby 1.9 I am annoyed.
I want to learn one programming language, not two, but which one should I really learn? My answer seems to be both at the same time. It seems to be the most sense to really learn Ruby 1.9.x because that's the future of Ruby programming. As an example of Ruby 1.9.x unfriendliness, say you are a Ruby beginner and you want to get Ruby up and running at work as fast as possible for a little task that needs to be done. Perhaps it doesn't really matter much if you use or learn Ruby 1.8.x or Ruby 1.9.x or both, but as a newbie you just don't know.
Comments DavidNcl 24 August 2009 at 4pm Troll. JavaScript Eye for the Ruby Guy. Ruby Best Practices - Should I Tap that Hash? (Ruby 1.9 Style) UPDATE: Be sure to read the comments. I’ve already learned a lot from them, and you might, too. Though the Ruby Best Practices book covers Ruby 1.9, it is decidedly not a “Ruby 1.9 Best Practices” book. The reason for this, of course, is that common idioms for Ruby 1.9 haven’t evolved yet. Let’s work together to change that. Every week until Ruby 1.9.2 comes out, I’ll be coming up with short, manageable bits of Ruby 1.9 code for discussion, as part of a “Ruby 1.9 Style” series. These should not be taken to be authoritative in any way, but instead work as conversation starters so that we can move forward as a community and separate the good from the bad when hacking code on Ruby 1.9. Rather than describing in detail how this series will work, I’ll just begin with some real content and you can get a sense of the format from that.
Object#tap, a seemingly benign addition. Ruby 1.9 gives us tap. >> [1,2,3].map { |x| x + 1 }.tap { |y| p y }.inject(:+) [2, 3, 4] => 9 def tap yield(self) self end. Raganwald. A tornado of razorblades. Beautiful Blocks. The following blog post is a direct excerpt from the Ruby Best Practices book. If you’ve been enjoying this blog, you’d probably love the book, so I’ve decided to release some content here to give you a sense of what to expect. Enjoy! UPDATE: For those coming from other languages, Ruby’s code blocks are inherently closures , and provide syntactic sugar for methods that accept Proc objects (Ruby’s anonymous functions). While not strictly necessary for understanding this article, a solid grasp on what closures are and how they work will take you far. In Ruby, code blocks are everywhere. >> ["Blocks","are","really","neat"].map { |e| e.upcase } => ["BLOCKS", "ARE", "REALLY", "NEAT"] But other blocks don’t really iterate over collections—they just do helpful things for us.
File.open("foo.txt","w") { |f| f << "This is sexy" } File.open("foo.txt","w") { |f| f << "This is sexy" } instead of forcing us to write this: file = File.open("foo.txt","w") file << "This is tedious" file.close. The all-thing. Ruby 1.9 has both fibers and continuations. The two are often mentioned in the same breath. They do vaguely similar-sounding things, and are implemented in Ruby 1.9 with similar mechanics underneath the hood, much as how continuations and threads were implemented with the same underlying mechanics in Ruby 1.8 [PDF, p. 14]. But implementation similarities aside, continuations and fibers have very different semantics. A fiber behaves as a thread without preemption. Like a thread, you create it, and it eventually dies; unlike a thread, you must manually call yield and resume to transfer control in and out of it, instead of just letting the runtime call them for you whenever it feels like it.
What’s nice about fibers is that, since you keep explicit control of the order of execution, you can get thread-like behavior without all the hassle of mutexes and synchronization. What about continuations? What’s nice about continuations is that you can use them to implement control structures. The Evils of the For Loop. I've never liked the for…in loop in Ruby. I cringe every time I see it in examples (Rails seems to put it in views a lot) and I tend to switch it to an each() call. It really bugs me. That's mostly just my gut reaction, but if I had to put it into words it's that I fell in love with Ruby's iterators early on and for just doesn't seem to fit in well with them.
I don't think that's just my emotions talking either, it really doesn't fit in. First, let's see what I'm talking about. . (1..3).each { |i| p i } # >> 1 # >> 2 # >> 3 I doubt that surprises anyone. For i in 1..3 p i end # >> 1 # >> 2 # >> 3 That's the same thing. Class MyEachThing def each yield 1 yield 42 yield 2 yield 42 yield 3 end end for i in MyEachThing.new p i end # >> 1 # >> 42 # >> 2 # >> 42 # >> 3 However, there's one tiny difference that ends up being pretty critical. For i in whatever # ... end # translates to: i = nil # assuming i didn't already exist whatever.each do |i| # ... end a = 1 (3..5).each { |a| } p a # >> 5.
Tighter Ruby Methods with Functional-style Pattern Matching, Usi. Ruby doesn’t have overloaded methods, which are methods with the same name, but different when you consider the argument lists and return values. This would be somewhat challenging to support in a dynamic language with very flexible options for method argument handling. You can “simulate” overloading by parsing the argument list and taking different paths of execution based on the structure you find.
This post discusses how , a hallmark of , gives you powerful options. First, let’s look at a typical example that handles the arguments in an fashion. Consider the following Person class. You can pass three arguments to the initializer, the first_name , the last_name , and the age . Require "rubygems" require "spec" class Person attr_reader :first_name, :last_name, :age def initialize *args arg = args[0] if arg.kind_of? The condition on the # 1 comment line checks to see if the first argument is a Hash . Another approach that is more flexible is to use duck typing, instead. Final Thoughts. Ruby Class Tutorial. Classes and interfaces are the primary building blocks of a typical Java application. Classes are the blue prints used to create objects in a running system. In contrast to Java, Ruby’s building blocks are classes, modules, and mixins. In this post we will take a tour of classes in Ruby. Classes To get started, lets define a basic Person class.
The above class is the simplest class type we can define in Ruby. The first thing you will notice is that the curly braces that are so pervasive in other programming languages are omitted here. This is not a typo. As in Java, we use the class reserve keyword to define a class type and the class name is capitalized in camel case. So far the Person class defined above is not even interesting enough to instantiate. There is a lot going on here so lets try to step through the code. Ruby is widely known for its concise language constructs and typing in a setter and getter for each individual instance variable is so 1999, that is to say so Java-like. The Ruby Language @ Programming Ruby. Roles Testing For Security. Ruby Essentials. Ruby books for 2009. RE: Ten Things a Java Programmer Should Know About Ruby. "Lets" organize our Ruby Code. Plato Says Knock You Out.