0
Digg me

e Logo At DemoCampMontreal4, I showed the results of time spent programming Ruby and RubyOnRails within the excellent e Text Editor for Windows. You can read about the presentation in my DemoCampMontreal4 report here at YashLabs, MTW and Marc-André Cournoyer’s blog.

e Text Editor and the extensible Bundle system

e is compatible with (the Mac OS X-only) TextMate bundles and can load in its snippets for faster Ruby and Rails programming. However, I also wanted to have quick access to all the methods associated to the common Ruby data structures:

  • String
  • Array
  • Hash
  • Fixnum
  • The Design

  • A keyboard shortcut for launching the menu
  • A menu displaying all methods is displayed
  • From the menu, the user can scroll and select the method or jump to it with a keypress for the first letter of the method
  • On selection, the menu disappears and the appropriate method name is inserted at the current cursor position
  • Ruby’s reflection capabilities

    Ruby logoRuby is a great object-oriented language. In Ruby, everything is an object and hence all the object-oriented principles I learnt are implemented in Ruby quite well and simply, which is more than can be said for C++ and Java. For instance, in Ruby, you can do this:

    10.times

    or

    "Hello".length

    Ruby is great for introspection as it has good reflection capacities – an object can provide information about its internals. The inbuilt .methods method gives all the methods associated with a data structure. e.g.

    puts Array.methods.sort.inspect

    gives


    ["< ", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "__id__", "__send__", "allocate", "ancestors", "autoload", "autoload?", "class", "class_eval", "class_variable_defined?", "class_variables", "clone", "const_defined?", "const_get", "const_missing", "const_set", "constants", "display", "dup", "eql?", "equal?", "extend", "freeze", "frozen?", "hash", "id", "include?", "included_modules", "inspect", "instance_eval", "instance_method", "instance_methods", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "method", "method_defined?", "methods", "module_eval", "name", "new", "nil?", "object_id", "private_class_method", "private_instance_methods", "private_method_defined?", "private_methods", "protected_instance_methods", "protected_method_defined?", "protected_methods", "public_class_method", "public_instance_methods", "public_method_defined?", "public_methods", "respond_to?", "send", "singleton_methods", "superclass", "taint", "tainted?", "to_a", "to_s", "type", "untaint"]

    However, [].methods.sort contains additional methods not contained within Array as shown by:


    res= [].methods - Array.methods
    puts res.inspect

    This gives the additional methods of []:

    ["select", "[]=", "transpose", "< <", "&", "indexes", "partition", "map!", "uniq", "empty?", "fetch", "values_at", "*", "grep", "+", "shift", "clear", "-", "reject", "insert", "reverse!", "indices", "delete", "first", "concat", "member?", "flatten!", "|", "find", "join", "delete_at", "each_with_index", "nitems", "unshift", "index", "collect", "fill", "all?", "uniq!", "slice", "length", "entries", "compact", "last", "detect", "delete_if", "zip", "each_index", "map", "sort!", "assoc", "rindex", "any?", "to_ary", "size", "sort", "min", "push", "find_all", "each", "slice!", "pack", "reverse_each", "replace", "inject", "collect!", "rassoc", "at", "reverse", "compact!", "sort_by", "max", "reject!", "flatten", "pop"]

    Therefore, instead of Array.methods, I’d rather get [].methods.

    Cygwin

    Cygwin logoCygwin’s great UNIX-like programming environment is used by e for the bundle system. This is interesting because from there you can run Ruby code within the e Bundle system and communicate with Cygwin through to the Operating System.

    There’s a great post by Ben Kittrell describing how he made a great Mac-like environment for Rails development on Windows using Cygwin.

    wxCocoaDialog

    wxWidgets logoCocoaDialog is a lightweight Objective-C application for Mac OS X to provide easy access to common GUI widgets and is particularly suitable for object-oriented scripting languages.

    Fortunately, some kind soul ported CocoaDialog to use the cross-platform and open-source wxWidgets toolkit. Actually, it is e Text Editor and its TextMate-compatible bundle system that gave rise to wxCocoaDialog.

    And in this wxCocoaDialog port, we have three additional runmode items not present in CocoaDialog on Mac OS X, including…menu!

    Putting it all together

    Provided you have e installed (wxCocoaDialog comes with it) as well as Cygwin and Ruby for Cygwin, here is how to proceed.

    1. In e, press CTRL-SHIFT-B to open the Bundle Editor
    2. On the left tree-view pane, select Ruby
    3. Click on the big + button lower down and choose New Command
    4. Name the command RubyMethodsString (or anything suitable for you)
    5. Paste in the following code I wrote which connects Ruby, Cygwin, wxCocoaDialog and e. Be careful when pasting as currently the code formatting plugin does weird things with quotes – all the quotes are straight except after index= – the outermost ones really are backticks to access the system

    6. #!/usr/bin/env ruby

      #Access Ruby Methods for strings
      #August 2007 - Josh Nursing - josh.nursing AT gmail.com

      SUPPORT = ENV['TM_SUPPORT_PATH']
      DIALOG = SUPPORT + '/bin/CocoaDialog.exe'
      sel = ENV['TM_CURRENT_WORD']
      x = "--xpos #{ENV['TM_CARET_XPOS']} "
      y = "--ypos #{ENV['TM_CARET_YPOS']} "

      am="".methods.sort

      menu=[]

      #Populate menu with formatted entries
      am.each do |w|
      menu.push "'" + w.to_s + "' "
      end

      #CocoaDialog menu
      index =`"#{DIALOG}" menu --items #{menu} #{x} #{y}`.to_i - 1

      #Insert the selected method text at caret position
      print '.' + am[index]

    7. In the upper right corner, as Environment, select Cygwin
    8. Lower down, select as Input: Selected Text or Word
    9. As Output, select Insert as Text
    10. As Activation, select Key Trigger and press a key combination. I used CTRL-SHIFT-Y
    11. Close the bundle editor and in your Ruby file within e, after a string variable name or string, press the key shortcut
    12. e menu extension for Ruby Programming

    13. Navigate the menu either with the Up or Down Arrows or jump straight to a method by pressing its first letter
    14. e menu extension for Ruby Programming 2

    The selected method including the dot is inserted within your code in e.

    From here you can derive the very similar codes for the other data structures and add them with new shortcuts. My shortcuts are in a row on the keyboard (CTRL-SHIFT-Y, -U, -I, -O).

    This menu extension can be accessed when you’re developing a Ruby on Rails application as well.

    This shows how e can be usefully extended to work better with your favorite programming language.

    • Share/Bookmark
     

    Hacking IronRuby

    0
    Digg me

    IronRuby imageJohn Lam of Microsoft released IronRuby this July 23rd. IronRuby is destined to enable the use of Ruby with .Net to build Windows applications. It targets the Dynamic Language Runtime, which Microsoft plans for IronRuby, IronPython and VBx, a dynamic version of Visual Basic. This post is a tutorial for hacking IronRuby.

    In this tutorial I’ll show:

  • How to build IronRuby and test it, including a simple .Net interop test
  • How to set up a Visual environment to hack IronRuby
  • How I hacked the IronRuby C# source code to fix a bug about string concatenation in Ruby
  • How I extended IronRuby with a new method implementation with the Visual environment
  • A few months ago, I emailed John about the possibility of using his RubyCLR, the precursor to IronRuby, to integrate with open-source IDEs. John was quite open to the idea. This new project renews my interest as already, IronPython has been integrated within the Visual Studio environment, and it would be great to tackle the VS integration of IronRuby in the future.

    I checked out the source code to IronRuby in its really early pre-Alpha stage (so you should expect incompleteness and bugs). Antonio Cangiano wrote a long post about this, but this first release is under Microsoft’s Permissive License, so that anyone can look at the code and modify it.

    1. Building IronRuby

    1. Make sure you have the IronRuby source code and that you have extracted it, and also the .Net framework installed.

    2. Because of a bug in Microsoft’s .Net framework installation, paths to the framework or the corresponding system environment variables are not set correctly. Check the path to your latest version of .Net framework by looking in the Windows\Microsoft.Net directory.

    Mine is: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

    3. In IronRuby’s installed directory, edit Build.cmd and replace
    %frameworkdir%\%frameworkversion% by your full path to your .Net framework dir
    .

    4. Save Build.cmd.

    Mine contains
    C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\msbuild.exe /p:Configuration=Release /t:Rebuild IronRuby.sln

    5. Launch Build.cmd from the command line.

    IronRuby should now build successfully.

    2. Testing IronRuby

    1. Launch rbx.exe in the Bin\Release subdirectory and try a simple Ruby command like 3+5 or puts ‘Hello!’

    2. A simple .Net interop test:

    require 'System.Windows.Forms'
    f=System::Windows::Forms
    f::MessageBox.show "Hello from .Net!"

    IronRuby test

    3. A string test which fails:

    IronRuby bug

    Here, we can see that string concatenation unfortunately modifies the first argument. We’ll see how to fix this in IronRuby’s source code in a short while, but first we’ll set up a nice Visual environment to code in.

    3. Setting up Visual C# Express 2005 to hack IronRuby

    1. Download Visual C# Express 2005 and install it. Do register the software.

    2. Load the IronRuby solution file, IronRuby.sln, in the Visual C# Express 2005 IDE.

    3. You can then build IronRuby straight from the IDE and also modify it which we will now see by going through fixing the bug encountered above.

    4. Hacking IronRuby to fix the string addition operation bug

    After grasping the overall source-code structure, I narrowed down the bug to the Ruby\Builtins\MutableStrings.cs file and the Concatenate(MutableString self, MutableString other) implementation of RubyMethodAttribute “+”:

    [RubyMethodAttribute("+", RubyMethodAttributes.PublicInstance)]
    public static MutableString Concatenate(MutableString self, MutableString other) {
    return self.Append(other);
    }

    self.Append(other) was obviously effecting the concatenation but modifying self (as that’s what Append should do) and returning the result.

    To fix this in C#, I needed to instantiate a new temporary MutableString object to which I could in turn append self and other and return this instead:


    MutableString result = new MutableString();
    return result.Append(self).Append(other);

    Hacking IronRuby

    Once you’ve modified an existing IronRuby implementation, you can Build the solution within the Visual C# IDE (F6).

    After a successful build, you can browse to the IronRuby Bin\Debug directory (or Bin\Release if you set it up this way within Visual C#) and check whether rbx.exe is recently timestamped.

    Just double-click on rbx.exe to launch it and to check the bug fix:

    IronRuby patched

    Don’t forget to exit the debug version of rbx if you’re doing other modifications or you won’t be able to build it.

    5. Extending IronRuby with new Ruby methods implementations using Visual C#

    Here, we’ll be adding a new Ruby method implementation to the Ruby Builtins classes, so a simple Build of the code would not work, as there is intermediate C# code which has to be generated automatically thanks to a small program named ClassInitGenerator.

    There’s a bad path setting in one of the files we’ll need, so we have to fix this first:

    1. Browse to the Src\Ruby\Builtins directory

    2. Right-click the GenerateInitializers.cmd file and select Properties.

    3. Uncheck the Read-Only attribute and click Apply, then OK.

    4. Right-click the same file again and select Edit.

    5. Remove the initial ‘..\’

    Your new file should contain:

    ..\..\..\Bin\Debug\ClassInitGenerator > Initializer.Generated.cs

    6. Save the file.

    As Antonio Cangiano of IBM Toronto’s Software Labs and others rightly pointed out, a simple float division will throw IronRuby astray:

    IronRuby Float Divide missing

    That’s because the Ruby “/” method for floats within the Builtins\FloatOps.cs file is not implemented yet.

    Here’s my simple code for the IronRuby implementation of the Ruby “/” operation:


    [RubyMethodAttribute("/", RubyMethodAttributes.PublicInstance)]
    public static double Divide(double self, double other)
    {
    return (self / other);
    }

    Here are the steps to recreate an extended IronRuby with the IDE:

    1. Save the FloatOps.cs file (or the project)

    2. Right-click ClassInitGenerator in the solution tree-view and select Build

    3. Browse to Src\Ruby\Builtins and launch GenerateInitializers.cmd. A new Initializer.Generated.cs file will be generated. If the Visual C# IDE asks for it to be reloaded, click “Yes”.

    4. Select the Solution and Build it (F6)

    5. Browse to the \Bin\Debug directory and launch rbx.exe to test it:

    IronRuby Float extended

    You can now hack away at IronRuby with the Visual C# IDE. Microsoft will be accepting outside contributions to the source code which is expected to be on RubyForge by the end of August.

    Other interesting posts about IronRuby:

  • Scott Guthrie’s demonstration of IronRuby with .Net 3.x and Windows Presentation Foundation (WPF)
  • Scott Hanselman’s post on IronRuby and WPF with a C# client.
  • Antonio Cangiano’s post “Is IronRuby mathematically challenged?
  • Seo Sanghyeon has additional ideas about extending IronRuby
  • Miguel de Icaza’s post
  • Josh Holmes – IronRuby = (Ruby + .Net)!
  • Ola Bini – The IronRuby scoop
  • Ryan Stewart at ZDNet blogs
  • Additional thoughts

    This is a great milestone achieved by John and the team and I would love to see Ruby used to produce full-fledged Windows apps. Given Microsoft’s horrendous track record at supporting standards, and habit of ‘extending’ technologies to extinguish them later on, I want to see where this will go and I am also watching Microsoft’s sudden embracing of the terms ‘Open Source’.

    However, for successful people and teams, history is not a perfect image of the future as they can transcend that.

    John’s work on RubyCLR previously and IronRuby for the DLR today is testament to his great hacking skills and success at integrating Ruby and the .Net framework.

    Well done, John.

    • Share/Bookmark
     
    0
    Digg me

    Google Calendar synced with Thunderbird and LightningWith the release of the latest version of the open-source calendaring application Sunbird, Mozilla has also released the Thunderbird extension Lightning.

    Until now it wasn’t really possible to have two-way synchronization of your local Lightning calendar with Google Calendar. In this post, I show you how to do this so that an event added or edited in Google Calendar will appear in Lightning, and vice versa automatically. For Windows XP you should apply the XP timezone patch, but for all other Operating Systems, like Mac OS and Linux, the steps should work the same.

    Requirements:

    1. If you have Windows XP: XP timezone patch

    2. Google Calendar

    3. Mozilla Thunderbird – The best open-source email program.

    4. Provider for Google Calendar add-on

    5. Lightning – Thunderbird calendar add-on

    Install the timezone patch if necessary. If you already have Thunderbird and a Google Calendar account, then:

    1. Download and install the Provider for Google Calendar add-on for Thunderbird

    2. Download and install the latest Lightning add-on for Thunderbird

    To do these two steps above, you must:

    a. Right-click and save the extension in a local folder

    b. In Thunderbird, go to Tools->add-ons

    c. Click on the lower left “Install…” button and then find the two add-on files you saved (with the .xpi extension)

    Once the extensions are installed, check whether Lightning has correctly determined your timezone, and if not, set it manually in Thunderbird:

    Tools->options->Lightning->Timezone tab

  • Now, log into your Google Calendar and choose the calendar (if you have more than one) you want to sync with. Add some new test events if you wish.
  • On the lower left pane next to your calendar, click the blue down arrow, and select Calendar Settings.
  • On the settings page, go down to your Private address and click the orange XML button.
  • Right-click on the address shown in the new window and Copy Link Location.
  • In Thunderbird’s lower left pane, click on the Calendars tab, and then click on the New… button.
  • Select “On the Network” in the new window which appears. Click Next…
  • Select “Google Calendar”, and then paste the private address you copied into the Location entry. Click Next.
  • Give a name to your Calendar and choose a color. Click Finish.
  • Enter your password for your Google Calendar account and check the box so that Password Manager remembers it.
  • You should find your events appear magically in Thunderbird.

    Now try adding a new event in Thunderbird and Reload the Google Calendar page in your browser. Then, try editing an entry in Thunderbird and Reload the page in Google Calendar.

    There you go, two-way sync between Thunderbird and Lightning and Google Calendar!

    Now, when you see an interesting event on Upcoming or any other site which uses microformats, you can easily add that event to your Google Calendar with a single click, thanks to Firefox and the Operator add-on. If not, read my previous post on Enhancing calendar scheduling with Microformats.

    Once you’ve done that, your event is both in Google Calendar (so that you can check your calendar from any online computer) and in Thunderbird (so that you can check your calendar even when offline).

    The world just got a whole lot better.

    • Share/Bookmark
     
    0
    Digg me

    We have the best software to convert pdf to word documents as well as pdf to excel. Our server side PDF converter makes it easty to convert and create PDF files at Investintech.com

    TV:

    1. MIT World Videos

    Filmed presentations from the MIT School of Engineering professional education program. The public debate between Ray Kurzweil and David Gelertner about AI was interesting.

    2. TED Talks

    Clips of past talks at the TED Technology-Entertainment-Design yearly conference.

    Hans Rosling’s presentation is fantastic. He shows how information is still hidden beneath our usual file formats and in various databases, and demonstrates new ways of revealing and analyzing this information. I was happily surprised to see Mauritius feature prominently way up there on the right of a graph.

    You can find more information at the GapMinder site and interact with the interface which accesses the data at Google’s GapMinder World 2006 Tool.

    3. Best Tech Videos

    All sorts of Technology-related videos including clips of conferences, including Google’s TechTalks or EngEdu as they’re tagged on Google Video.

    4. Google Video – Documentaries

    University:

    1. MIT OpenCourseWare

    It is expected that by the end of 2007, all the courses by MIT will be available online freely. That’s going to be historical.

    2. University of California – Berkeley Webcasts

    Videos and podcasts from UC Berkeley.

    3. Wikiversity

    A free learning collaborative resource for the masses, by the masses.

    4. ShowMeDo

    Tutorials in screencast form or videos.

    In a previous post, I had mentioned that you could watch PBS’ Nova online.

    • Share/Bookmark
     
    0
    Digg me

    microformats logo Have you missed some event lately because the information about events is dispersed and fragmented and it’s boring to have to type things in your calendar?

    I will show you how to improve the scheduling of activities in an online calendar by automating much of this process by using Microformats.

    Microformats enable machine readability but additionally add meaning to chunks of text and other data. That means that these chunks of information also become machine ‘understandable’. In turn, this leads to automated processing of semantically useful data.

    The implications for building an Artificial Intelligence with the Semantic Web are staggering but in the meantime, I just want to tell you about a practical application of Microformats which is useful today itself, namely how to make good use of the hCalendar Microformat.

    What you should use:
    1. Firefox. You are using Mozilla’s Open-Source Firefox, aren’t you? If not download it.

    2. Operator. A Firefox extension or addon by Michael Kaply of IBM, which detects Microformats and enables you to act on them. Install it and restart Firefox and restore your session to come back here. Michael just opened up Operator’s source code. Thanks for that and for Operator Michael.

    3. Google Calendar. Get an account with Google and login.

    4. Upcoming.org. Yahoo’s event site which has support for Microformats.

    On installing Operator and relaunching Firefox, you should have a new thin toolbar. Mine shows: [Export Contact | Google Calendar | Google Maps | Flickr | Del.icio.us | Technorati]

    Now, head to upcoming.org and as search tags, type in, for instance, ‘Montreal’. This should list all events locally. It would be much more helpful if upcoming.org also provided Microformats on this list of events but currently it doesn’t.

    MTEBFast II

    Click one of these events. For this example, I chose the forthcoming Montreal Tech Entrepreneur Breakfast II launched by Ben Yoskovitz.

    GoogleCal1

    Operator detects the hCalendar Microformat content and add “(1)” next to the [Google Calendar] button among other things.

    GoogleCal 2

    Click on this button and the events information is automatically added to Google calendar’s event form. You can then save the event into your calendar.

    Voilà. You now have a way to rapidly find and integrate events within your online Calendar with nothing to type – just clicks.

    Now, it would be more interesting if people blogging about events would take the time to add Microformats to the information. One way to do this is to use the hCalendar Creator by Ryan King, based on previous work by Tantek Çelik. It also automatically add tags so that you can found similar events on eventful.com, another web service which is also using Microformats. Similarly here, Eventful does not provide the Microformat information in the list view.

    Check my past post about DemoCampMontreal1. Operator detects it immediately because that informative chunk of text was microformatted with hCalendar information by using the hCalendar creator.

    You can read more about Operator on Michael’s blog and on the Mozilla blog.


    • Share/Bookmark
     
    0
    Digg me

    In this section, we’ll see how to write classes in Ruby. We will also see how Ruby helps greatly to reduce class development time thanks to symbols. And lastly, we will see how to reuse our classes.

    Note here that I am not covering object-oriented principles. I assume you are already somewhat familiar with these.

    5.1 Creating Classes and Accessing Internal Variables

    We will create a simple Car class in Ruby with an internal variable for its brand. Note that the class name must begin with a capital letter.

    In your favourite editor, type the following:

    class Car
    def initialize(brandname)
    @brand = brandname
    end
    end

    Now that we’ve written the contents for the initialize method, you can create new car objects by passing an initial argument for the brand:

    myCar = Car.new("Lamborghini") or myCar2 = Car.New "Lamborghini"

    Now, note here that because of encapsulation (an important principle in Object-Oriented programming), the internal variable @brand of your object is not directly accessible.

    You cannot yet type:
    1. To access the value: puts myCar.brand
    nor
    2. To write a new value into it: myCar.brand = "Vektor"

    Before you can do this in any OO language, you must write what are called “getter” and “setter” methods. For example, in the above Car class, we would write a getter method for the brand thus:

    def brand
    return @brand #This is a comment: in fact, you could even omit the return keyword ;p
    end

    Try it in your IDE (add this “getter” method after the initialize one) and see that this time around, you can get the brand name by invoking: puts myCar.brand

    Similarly, for the “setter” method, we would add this to the class:
    def brand= (brandname)
    @brand = brandname
    end

    Add the above to your Car class and try it by changing the brand of myCar:
    myCar.brand = "Vektor"
    puts myCar.brand

    So, your Car class should now look like this:
    class Car
    def initialize(brandname)
    @brand = brandname
    end

    def brand
    return @brand
    end

    def brand= (brandname)
    @brand = brandname
    end
    end

    5.2 Attribute Symbols: Ruby’s shortcuts for Rapid Development and Prototyping

    Now, it would be more interesting if we could input a more complete set of details about our cars. Let’s say we would like also to be able to get and set the Model, the Year, the Colour, the Maximum speed, etc… But this entails having to write a getter method and a setter method for each of these attributes! Not very interesting, isn’t it? Time-consuming? Certainly!

    In Ruby there is a shortcut that allows us to do the same thing but much more rapidly and succinctly.

    In your Car class, instead of writing the getter method, just type this:
    attr_reader :brand

    This makes :brand a symbol which will be expanded internally and automatically into a getter method for you! attr_reader specifies that the internal variable @brand will be read only.

    Similarly, the setter method is written thus:
    attr_writer :brand

    Fantastic isn’t it? No need to write those pesky getter and setter methods.

    So now, your Car class would rather be:

    class Car
    def initialize(brandname)
    @brand = brandname
    end

    attr_reader :brand
    attr_writer :brand
    end

    But wouldn’t it be interesting if we also had another way to easily specify that several attributes should be both readable and writable?

    Another shortcut does just that in Ruby: attr_accessor

    Therefore, here is how to rapidly prototype a class in Ruby:
    class Car
    attr_accessor :brand, :model, :year, :colour, :maxspeed

    def initialize(brandname, modelname, year, colour, maxspeed)
    @brand = brandname
    @model = nodelname
    @year = year
    @colour = colour
    @maxspeed = maxspeed
    end
    end

    or if you don’t need to initialize your object with values right away, simply:
    class Car
    attr_accessor :brand, :model, :year, :colour, :maxspeed
    end

    Now, to use this Car class you would simply type:
    myCar3 = Car.new

    and then, you could manipulate its attributes like brand and model as usual:
    myCar3.brand = "Vektor"

    Can you see how symbols help to drastically reduce design and development time in Ruby as compared to other languages?

    5.3 Reusing classes as modules

    Let’s assume that you wrote a great Person class and that several of your programs must use this class. It is good practice to reuse your existing code (er… especially if it is GOOD code, ok?).

    Ruby provide an easy way to do just this.

    Just save your Person class as person.rb. Then, when you wish to reuse that class in any new program, you invoke the file which contains the Person class fist, and subsequently use the class as you would normally:

    require "person.rb" # Note I am assuming the person.rb file
    # is in the same directory as your new program

    p1= Person.new

    Try it with your Car class, for instance.

    Note that if you have many constants and classes that you want to reuse, then use the ‘module’ and ‘end’ keywords to enclose all these into a reusable file.

    This concludes the introduction to Ruby. You do not need classes to write Ruby scripts, but if you do you will find that your code is better, more readable and maintainable. In other words, you will be benefiting from all the advantages of Object-Oriented programming.

    If you have come this far, I urge you to continue to explore programming in Ruby by perusing the various resources on the web. You can access a free version of the “Pickaxeâ€? book online and also “Why’s poignant guide to Rubyâ€?, replete with fox cartoons.

    When you are comfortable with Ruby programing, you can also try your hand at Ruby on Rails, the fantastic framework for easily developing database-driven web-applications.

    Happy programming with Ruby!

    • Share/Bookmark
     
    0
    Digg me

    4.1 Looping

    Note: a range in Ruby is denoted this way: 2..5 (from 2 to 5).

    a. The for loop:

    for i in 2..5
    puts i
    end

    IRB faithfully gives you 2, 3, 4 and 5. Note the in keyword here. Also note that the for loop in Ruby ends with end and not next as in BASIC.

    b. Using .times:

    In IRB, type: 3.times {puts "I get it!"}

    The sentence is output three times as expected. Nifty loop instruction, isn’t it? Note here that I am using {} to delimit a code block of a single line. For blocks with more than one line, use do and end as in the example below.

    c. The while loop:

    i=10
    while i>0 do
    puts i
    i -= 1
    end

    IRB outputs all values of i from 10 to 1. Note here the use of do and end to delimit the code block for the loop as there are several instructions. Also, see that Ruby enables ‘i-=1′, which equivalent to “i=i-1″, just as in C/C++. Both are correct in Ruby.

    d. Iteration

    You can easily iterate through the elements of an array using the ‘each’ method. In IRB, try:

    a=["A", "B", "C"]
    a.each {|x| puts x}

    IRB prints out all elements of the array a in turn. Note here the use of | |. This defines a type of assignment for the element at each iteration so as to process it right afterwards. i.e. on the first execution of the loop, x gets assigned “A”, and this is printed out. Then, thanks to ‘each’, the next element of the array, “B�?, is assigned and processed.

    Q: What do you think is the method for iterating the elements of a Hash?

    There are other ways of looping in Ruby, so have a look at the documentation should you need other constructs.

    4.2 Branching

    a. The if conditional

    In IRB, type:
    i=10
    if i==10
    puts i
    end

    IRB outputs 10.

    Note the difference, just as in C/C++ between assigning a value to i (i=10), and testing whether i is equal to 10 (i==10).

    There is a shorter version of “if” in Ruby, but use it for short lines:


    puts "Everything is all right!" if (2+2 == 4)

    Now try:
    if i==5
    puts i
    elsif
    puts i*i
    end

    You should see 100. Note the elsif keyword, NOT ‘elif’ nor ‘elseif’.

    b. The case-when-else conditional

    This expression is especially useful in a loop where the parameter tested changes. But I’ll show only the syntax for two or three tests here:

    case i
    when 10
    puts i
    when 5
    puts i*i
    else
    puts "unknown"
    end

    IRB shows 10. Try i=5 and then the same code to get 25. Also, try another value not included in the case statement and get “unknown”.

    With the knowledge you have, you can already write a plethora of useful programs. Practice building simple or bigger programs with the information you have learned up to now.

    Part 5

    • Share/Bookmark
     
    0
    Digg me

    Part 2: Basic Input/Output

    In this second installment, I describe basic input and output operations in Ruby, and especially some issue that can stump a newbie on Windows.

    In the first part, I recommended RDE as a learning IDE because of Autocomplete (it also has syntax highlighting). IRB, the interactive Ruby shell is also a great way to learn. It comes with your Ruby installation in the bin directory.

    In Ruby, you can output using puts or print. Typically, puts will also operate a carriage return/newline and puts will not.

    1. puts “Hello, World!” works, just as puts ‘Hello, World’. Print “Hello, World!\n” is another way of doing the same thing.

    2. In Ruby, strings are concatenated with the + sign. Print “Hello” + “World!” is similar to the above.

    3. If you want to concatenate and also output a numerical value, you usually have to use the .to_s method. i.e. print “five=” + 5.to_s.
    .to_s means convert to string.

    4. There is a nice shortcut for variable substitution in Ruby. Let’s say you have a variable, age which is equal to 25. Then, print “His age is #{age}” will evaluate the age variable and substitute it into the string as soon as the #{ is encountered by the interpreter.

    You can do input in Ruby using the gets command, like in:
    print "Enter your age:"
    age = gets

    However, there is buffered output in Ruby and you will be surprised or stumped when working with Ruby on Windows, as the previous command will first wait for your entry and then output the print string!

    What you can do here is to just turn off the buffered output before anything else using:
    $stdout.sync = true

    This done, the functioning of Ruby becomes intuitive for the newbie with some performance hit (not important when learning).

    Part 3

    • Share/Bookmark
     
    0
    Digg me

    This is the first part of a quick and easy 5-part tutorial for the Ruby programming language. I initially sent it to Rubidius, the local Ruby User Group I founded, as well as to my Local Linux User Group. It’s free as in free beer. Learn Ruby in one hour. At least the basics. Seriously, it will take you about an hour for the whole. Enjoy.

    ———————————————————————-

    One-hour Ruby
    An introduction to the Ruby language in 5 easy pieces

    by

    Josh Nursing

    Introduction

    This is a very brief introduction to some of Ruby’s syntax. This tutorial is designed to get you up and running with Ruby and writing scripts as rapidly as possible. It is not intended as a complete Ruby course nor as a course for Object-oriented principles. You will find it especially useful if you already know programming in some language other than Ruby and want to see how it is to program in Ruby. And it only takes an hour of your spare time.

    Part 1: Variables

    If you haven’t yet installed Ruby and would like to try it, it is readily available for Linux, Mac, and Windows:

    http://www.ruby-lang.org/en/20020102.html

    A nice install for Windows is Curt Hibbs’ one-click installer. It comes with a good IDE called FreeRIDE, but for learning, I recommend RDE as it contains Autocomplete and shows you the methods of a class, etc…

    Let’s see briefly how variable are declared in Ruby.

    In Ruby, part of the syntax denotes the type of locality of a variable.

    1. A global variable starts with a $, like in $MaxItems
    2. A local variable starts with lowercase, like in myval

    Similarly, constants are defined in Ruby by using a name which starts with an UPPERCASE, like PI = 3.141592653 or Pi = 3.141592653.

    Note here that we never had to define the actual type of variable. It isn’t necessary for us to define that $MaxItems is an integer. Ruby will infer this automatically. This saves a lot of time and makes you more productive.

    Now, let’s see the cases of variables when you are writing classes and using objects (instances of classes).

    1. A class variable starts with @@, like in @@name
    2. An object instance variable starts with @, like in @address

    Don’t worry about classes and objects right now as we’ll see them again in the last section.

    Part 2

    • Share/Bookmark
     
    1
    Digg me

    (c) Josh Nursing

    I am a huge fan of the Kurzweil K2 series synthesizers and their seminal V.A.S.T. architecture which is still one of the most powerful synth engines today.

    But with power comes complexity. Hence, as a long-time contributor to the Kurzweil mailing lists for about ten years, I usually teach people how to harness the raw synthesis power of these synths.

    On the mailing list once, a reader asked if it was possible to re-create sounds that The Prodigy used on their album “Voodoo People”. Although somebody else was saying that The Prodigy probably used ‘racks of gear’ and that it was impossible to do the same on the Kurzweil K2000, I proceeded to describe step by step a few avenues to explore. The reader replied that during the week-end, he had achieved even better sounds thanks to my advice.

    Subsequently, I wrote several advanced tutorials for the Kurzweil synthesizers based on more than 15 years of experience with sound synthesis.

    These advanced tutorials for the Kurzweil K2 series synthesizers have been edited from their previous versions and reproduced here. I have added screenshots to make them easier to follow. The screenshots are provided by YashLabs’ KurView, a brilliant software remote controller for the Kurzweil K2 series synthesizer.

    (more…)

    • Share/Bookmark
     
    0
    Digg me

    (c) Josh Nursing

    This tutorial shows how to use some synthesis tricks to enable fake effects for programs within the Kurzweil K2000 synthesizers and above with the V.A.S.T. architectures.

    The Kurzweil K2000 has a global multi-effects processor. Independent WET/DRY mixes can be achieved with the panner algorithms. Having different effects for each channel is normally impossible on the K2000, K2500 and K2600/K2661 (instead you’d use the KDFX studio with its 4 strips).

    If your requirements are not too extreme, you can fake program flange, delays and reverbs using envelopes, LFO’s and other hacks on the K2000.
    (more…)

    • Share/Bookmark
     
    0
    Digg me

    (c) Josh Nursing

    This is a tutorial about using your Kurzweil K2 series synthesizer and emulating some of the features found on the Korg WaveStation, especially Wave Sequencing.

    1. Vector Synthesis.

    There is no difficulty in emulating vector synthesis at all. The joystick found on WS keyboards is just a controller with two axes: x and y. Simulating the joystick therefore entails using two real-time controllers on the Kurzweil synthesizers. One is used as a source on one or more parameters. The other is set to control other parameters of the same program. The simultaneous use of both controllers is similar to selecting a point in a Cartesian coordinate system, which the joystick enables you to do.

    2. WaveSequencing.
    (more…)

    • Share/Bookmark
     
    3
    Digg me

    (c) Josh Nursing

    This tutorial shows how you program your Kurzweil K2000 (or K2500, K2600, K2661) synthesizer and:

  • assign various song sequences to different keys so as to trigger them interactively. Furthermore, you will learn how to record your live triggering of the songs.
  • Record different arrangements on your song.
  • This is pretty much the same thing you can do within Ableton’s Live software, but on your Kurzweil synthesizer.

    When I upgraded a Kurzweil K2000 synthesizer from v2.xx to v3.18, I wanted to record whole sequences interactively into the sequencer, following on the interesting suggestions made by Keith Cowgill on his site.

    You can use the ARRANGE page to trigger different sequences through keys. However, I could not find a way to record my live pseudo-arpeggiations without retriggering the songs defined in the steps.

    Fortunately, there is a way to do this properly, but it’s not very clear from the manual (or rather it must be read more than once and thoroughly).

    So here’s a quick introduction to some really powerful aspects of the K2000’s internal v3.xx sequencer.

    First, if you haven’t read the introductory sequencing tutorial in the manual, please do, with your K2k besides you to get acquainted with basic operations.

    Now that you know how to create a sequence and save it, we’ll look more closely into the ARRANGE feature.

    Each song has an associated ARRANGE page. On that page you can associate steps to other existing songs, so that these ‘other’ songs will be played in sequence from step 1 to step x where x< =99.

    Follow the instructions below to try these powerful features:
    (more…)

    • Share/Bookmark