Video Transcript
Hello, I’m Nancy Strickland from IT Mentors. In this session, I’m going to be presenting an introduction to the syntax of IronRuby for Visual Basic Developers.
Syntax Basics
This session will focus only on syntax. It’s just about the code. So we’re going to be working most of the time just from the command line, typing in commands and executing them live. I will show you some script files and run them from the command line so you see how that works. But if you want to know about using IronRuby with Silverlight, or in Visual Studio or about other tools, then there’s another video called Fundamentals of the DLR, which is part of this series. And it covers those tools more but with less syntax. I’m going to assume that you already know how to obtain and install IronRuby and how to enter and execute commands. If you don’t, the Fundamentals of the DLR video also covers those things.
We’ll start with the basics, variables, expressions, loops, conditionals and functions and then we’ll cover using object orientation and interoperating with .NET and we’ll talk about how to access data external to the program and files or databases. Of course, I can’t cover all the syntax of a language in an hour, so I’ll try to present some basics that will get you started and then at the end of this session. I’ll give you some references you can use to get more information on your own.
I’m going to start IronRuby from command line with IR and I want to show you the warning message here. It says that local variables don’t work today in the console. That’s not a problem, we’ll just use globals but want you to see that what the message implies is that this may change and that gives me a chance to tell that IronRuby is a very new language. It’s still in Alpha, not even Beta yet. As of when this video was made in December 2008. So, realize that a lot of what I’m going to tell you could very well change in the future. New features could also appear that aren’t there now.
Now to exit, I either use control Z or I can type the word exit and then I’m going to restart and this time at the prompt which is there right angle brackets over here, I’ll do the basic “Hello World” which is just put as hello world and what happens when I do a “Hello World” in IronRuby is that it immediately processes the line I just entered so it prints out “hello world” and then it also returns the return value of the function put S, which in this case is nil, which means nothing. You’ll notice that like Visual Basic, IronRuby has no symbol to terminate lines.
Now, if I entered an expression like 2+2, I’ll get back the result of IronRuby’s evaluating the expression but this works only from the command line, so don’t get in the habit of doing it. It can be handy for quick interactive testing, but if you’re working with a script, you’re going to have to say print 2+2.
IronRuby processes expressions the same way everything else does, i.e., the meaning of this is that perform the exponentiation first. The exponentiation is the 2 stars. So, 3 * * * 2 means square 3. What this means is add 2 + 2, raise 3 to the power of 2, the two stars mean exponentiation and then multiply those together so 9 times 4 is 36, just like it would be anywhere. The rules are always the same.
You can also see that it uses the standard operators for addition, multiplication, that exponentiation is 2 stars **. It uses the normal subtraction and division symbols. and for the mod or modulus or remainder, whatever you call it, operator, it uses the percent sign. You can do integer arithmetic, so this returns a 2, or you can do an integer arithmetic if I divide 6 by 4, leaves me with a 1, that is the fractional point is dropped, not rounded. If I want to get the fractional point, I’ll have to do floating point arithmetic by putting a decimal point and then I can get it.
Now, unlike standard .NET type system, there’s only two numbers, two numeric types INT and FLOAT. You can mix them and the result here of mixing a FLOAT and and integer is a float answer. If you want, for some reason, an integer answer from that, I’m going to use a function to get that and it’s the to_i function. So, it takes the fractional point part and throws it away. Now, there’s two things to notice here, although it’s a function, it doesn’t parentheses after it, that’s because if a function doesn’t take an argument in IronRuby, you don’t have to put the parenthesis there. I put the parenthesis around the division part because otherwise that to_i would refer not to the result of division but to the 5 only, no reason to convert to an integer, it’s already an integer.
The opposite of this, if I divide 6 by 3 and want for some a floating point answer, is I can say 2_f and that gives me a floating point answer. Now I didn’t have to parenthesize the division here because just changing the 3 only to a float, worked because an integer divided by a float is still a float. Now I have been using put S to print out. I use that for the Hello World. IronRuby also supports the print command, the noticeable difference between put S and print is that print does not add a new line character at the end of the output, the put S does. And one more thing, comments. Comments start a pound sign, some people call it a hash mark and run from there to the end of the line. So it printed out hello and ignored the rest of that line.
Now, let’s look at variables. If you already know something about Ruby or some other dynamics, scripting language, you won’t expect Variables and IronRuby to be declared, they don’t have a declared type. At runtime, the variable will be typed based on the content it holds. So you can create a new variable and type it at the same time, just by assigning a value to it. Now that’s different from .NET languages where all variables have to be typed or the compiler won’t accept them. You may remember that in VB6, there was a variant type that could hold any data type but Visual Basic.NET doesn’t haven’t a variant type. It does have object type that can hold any type of object and you know, that unless you use option strict, VB.NET compiler doesn’t enforce strict data typing if you try to assign one data type to a variable of another type.
So, I can create a variable just by typing $X=3. The dollar sign prefix here is an access modifier. It means that X is a global variable and you remember the error message we got or the warning we got telling us to use global variables in the console. When I used the value in the variable, when I printed that out, I’m going to use the dollar sign there as well. Now, in the very next line, if I want to, I can take that X and I can change the value in it to a float. No problem, no complaint or I can even put a string in it. You can put any kind of variable in anything. It’s convenient and easy to be able to do this but you probably already realize that it’s also the cause of bugs that can be hard to find, e.g. if you accidentally reuse a variable name and reassign to it, the variable that was in it before just disappears without any warning.
By the way, I’m using single quotes for these strings but I could have used double quotes too and you can nest double quotes within single or vice versa, if you need to. You can also just use a single quote as an apostrophe within double quotes. You don’t have to do anything special like a character function or something else that you might need to do in VB.NET. Also, unlike VB, which requires control characters or the user of the environment class, you can back slash some characters to create special meaning so, e.g., if I say hello, backslash in, that means new line world. It will print out as hello world, but this only happens if you’re working inside double quotes. If you work inside single quotes, that backslash in is just a little
IronRuby is case sensitive so if I type put s x, I get an error, an error message, undefined method. Now the case sensitivity can cause another kind of bug. If I say X=3 and now I want to increment x, so I say x=$X+1, I want to increment x and it kind of looks like I’ve done that but if I print out the value in X, it’s still 3. That’s because I accidentally typed a capital X and so the incrementation didn’t happen, instead a whole new variable was created. Now Visual Basic, as you know will change your capitalization to appropriate capitalization for you and you’re not going to get that kind of help with IronRuby. And if you don’t happen to know this, an error like this right way, it’s the kind of bug that can be hard to find.
Here’s the basic syntax for a conditional. I’ll sit in to the value 14 and then, I’ll say if N is greater than or equal to 10. Now first of all, you’ll notice that there are no parentheses or anything around that N being greater than or equal to 10. There’s no then after it, and there will be an end key, word but it’s not and if, it’s just end. And you can see how after I’ve pressed the Dnter after that N, my prompt changed, it’s now ellipsis, it’s three dots and that shows that I’m inside a multi-line statement. .
The comparison operators like this greater than or equal are mostly the same as in VB except for a couple of them and one of them is that instead of a single equal sign for equivalence, it uses two. So, let me go ahead and put here and here I’ll do an elsif and it’s E-L-S-I-F, all one word for elsif. So, if I want to say if N is equal to zero, I have to use two equals == so if N is == to zero, then I’m going to do something else. I’ll do another ELSIF to show you the not equals it’s exclamation point equals, instead of the greater than less than, it’s != and I’ll put something here and finally, this ELSE is just like the ending else in Visual Basic. And I’ll put in between and then end to end my if statement.
And I see now that because I was talking instead of paying attention, I accidentally types what I was saying else if so, I’m going to repeat this and I’m going to show you this gives me a chance to show you that I can use my up arrows to walk back through my commands and save a lot of time. So I’ll just repeat each command until I get to the one that was a problem and that’s here. Oh, I don’t think I have this one yet, okay. And now, when I type end, it immediately processes that conditional and gives me my result high and then gives me nil, which is the value that was returned from that.
Another version you can use puts the IF and the end of conditional statement . So I’m going to say put s “hello” if-we’ll say something that’s definitely true- If 2 = =2 and it’ll print it. I could also say Print “hello” if 2 != 2. And of course, it won’t print anything. A lot of programmers like that form because it’s natural in English log. Do something if something is true. IronRuby also has a kind of an inverse if. It uses the key word unless. So I’ll assign 3 to A and then I’ll say unless A > 5, got to spell it right, and you can see that that’s logical unless A >5, print it. It wasn’t so it did. It can also be reversed so I can say, put as true unless something is true. Now if I say unless 1 is equal to 2, well it’s not so it is going to put true. Some programmers as I say use this form a lot cause it feels like English; do this unless something is the case.
Ruby also has a case statement which is like the select case statement in VisualBasic.NET. Let me show you what it looks like. I’ve written this up as a script. I’ve just written it in Notepad and given it a name with RB as the extension. And then I’ll be able to run this, I’ll show you how in just a minute from the console. Let’s look at the case statement which is right here. Charge is going to be assigned different things, depending on what the case with particle is. So, if the value in particle is electron, then negative will be assigned to charge. And if it’s neutron, neutral, etc. And then we have an else, the default which is undetermined. So charge would be undetermined if none of those applied. So we set up our case, we set a value in particles set up our case and thenwere going to print A particle. In this case, it would be neutron. A neutron has A and it would assign neutral charge.
So, let’s run it. I’m going over here and in order to run a script like this, I’m going to have to get out of my IronRuby interface. So I’ll do CTRL-Z, that’s the end of file character, press enter. And now I’m at a prompt, so I can type IR to start Ruby. But I’m going to give it an argument instead of just typing IR, I’ll put demo case RB and then, the IronRuby will run this script for me. And it prints out a neutron, has a neutral charge so that worked. Now you might have noticed that I did not use dollar signs before the variables here, that’s because I’m not working interactively on the command line now so I don’t need global variables.
A loop in IronRuby could a while loop, an until loop, a for or a for each loop. Here the while and until loops that use end as their delimiter. We’ll do one. Get into IronRuby here. I’ll set a value into X and then I’ll say while X is less than 4, we’ll print it out and then we’ll increment it $X+=1, which means take the value in X, add 1 to it and put the result back in X. And so it prints 1, 2, 3 and stops when it becomes 4. The opposite of that is an until loop. I’m going to go ahead and leave X at it’s current value and I’ll say until X is zero, print it out. And here I’m going to go ahead and decrement it in the same lines. So, I’ll decrement it and then I’ll put it out or print it out and there it goes, it was 4 so it decrements, decrements, decrements down until it’s zero. You can also put either the while or the until at the end of the loop. But if you want to do that, you’ll have to start the loop with the keyword begin. So, I’ll say begin, I’ll take $ X which is zero at the moment, add 2 to it (+=2), print it back out and put my end and then here’s my until, until X is 10. Remember I have to have equals equals and there it prints from 2 to 10 counting by 2s.
Those are while and until loops, there’s also ‘for’ loops and there’s several different ways you can do those, they all use curly brackets as delimiters instead of the end keyword. This, for example, is going to iterate 4 times. I say 1, up 2, 4, open my curly brackets and I’ll just put the word test here, close my curlys and it prints test 4 times. I can count down also 4 down to 1, open, put as test, close and it counts – you can’t see it, but it counted 4 times as well, it was just counting down. Now, in both of these, notice that that opening bracket had to be placed on the first line so that IronRuby knew that a multiline statement was coming out.
There’s another form you can use like this. I’m going to say 1 to 10 and then I’ll put steps so that I can say to increment not by 1 but by 2. And again I’ll put the word test here and I’ll get 5 of them. It counted from 1 to 10 but by 2s, so it only happened 5 times. Now those numbers in parentheses, the 1 dot dot 10, those are called a range and they’re inclusive so it’s one to 10 including both 1 and 10. Ranges are also used to do a kind of a for each loop that looks like this: 1 to 10 each and then I open my curlies and say what I want it to do. I’m going to have it do a put s without an argument so I’ll get 10 blank lines printed out.
IronRuby has an array data type. This is what it looks like. I’ll create an array by saying dollar sign test equal square brackets and this is going to be an array of strings although arrays in IronRuby can mix data types. You can see it’s square brackets and then each item in it is quoted. Now if I want to iterate through it, the easiest way is to use a for N loops so I’m going to say for and then my choice of variable, lets say I-N and the name of my array here. For each one, I’m going to print whatever it is. And then here’s my end. Now, I’m using print instead of put s on purpose here, cause I want to print it out across “This” “is” “a” “test” instead of one word on each line.
Now notice that I didn’t put a dollar sign in front of the I here, I did in front of the test but not the I, that variable I is local to the for loop. Now test was declared in one statement and accessed in another so I had to make it global so that they could see each other but the I is just used inside that loop. Now this behavior, remember could change in the future and in any case, it’s only a concern if you’re just working from the command line. When you’re working inside scripts, as we saw, it’s a different issue.
Arrays are zero based, so if I want to get a particular value out of that array, I’ll subscript it inside square bracket so put dollar sign test, square bracket zero, gives me the first element, the zero-th element of that array. It’s the same as using parentheses around an index in VB.NET. Now what an array hold is objects which means it can hold anything. So, I’ll create a new blank array here by using empty brackets. Now, L, dollar sign L, knows that it’s an array and that means that I can use it’s methods and one of them is the insert method. So, I’m going to say dollar sign L, insert and I’ll say at the fourth position, index four, which is the fifth position along, put the number 8. And you can see here that it’s showing me that everything up until there is now nil, nothing beyond the highest thing has a value but we have nil nil nil nil 8. Now I can insert something completely different. I’ll go to the second element, index 1 and put a string in there, just to show and now I have nil some string, nil nil nil 8. I can actually print with the whole array out at once, it can automatically iterate through it if I put S$L and you can see that those nils print out as blank lines.
You can extend the functionality of IronRuby by writing your own functions. Here’s a simple one, the key word depth means I’m defining a function and here’s the name of it, add one and here’s the argument to it, in this case we only have one but you could have multiple ones. If you did, you just comma separate them. Here’s the body of it, on returning a value, I’m augmenting whatever was passed in, incrementing it by 1 and then passing it back. There’s my end showing at my end of my function and I don’t get a return value, that just shows that my function was accepted and now I can use it. So I can say, add one pass it to value and I’ll get back of value that’s one greater.
Now there’s only line in this function definition but there could be whole bunches and in this particular case, the last line which is also the only line return to value but IronRuby functions don’t have to return to value or at least they don’t explicitly have to. You don’t have to have a line that says return. If you don’t explicitly have a return line, then that functional returns the value nil, which is nothing, so you don’t have to write a return but actually it is returning something. Now, unlike VB, there are not too separate things, procedures and functions, everything’s called a function and it always returns a value, it’s just that sometimes the value is nil.
Strings are arrays of characters and like in other .NET languages, it’s a zero based array. So if I assign “hello” to X, I can then print out the h or print out the ASCII value that’s at position zero,by using my subscripts, subscripting zero and I get 104, which is the ASCII value of that lowercase h. There is no separate character type; a character is just a string of length one and you can use a method or an index against a literal string, the same way you can use it against a variable. So I can say the literal string “hello “give me the first character and it prints out the same thing, the ASCII for that. Now, if I want to convert to a character, there’s a function called CHR and does that conversion for me so there’s my lowercase h.
In addition to simple indexing, where you just put one number in the square brackets, IronRuby has what’s called slice notation, you use two indices, separated by two dots so 2..4 and that means give me all this characters that have a subscript 2,3 or 4. So, I get the LLO. You can also change the characters in a string using index notation so I can say take that first character and change it and make it a capital H instead of a lowercase H. And then if i print out that string, you can see that it’s now capital H “Hello.”
You can concatenate strings, you can do that using the plus sign. We’ll use that here to change that back to a small lowercase. We’ll say x equals lowercase h +, we’ re concatenating here, we’ll take the slice from one to four, that’s the second to the fifth characters. And now, if I print out $x you can see that it’s lowercase again.
Now there’s a function that will convert number to strings, it looks like this so I’m going to put this in the $X also. This would put the number 14 at the $X but if I say 2S, it doesn’t put the number 14, it puts the characters 1, 4, see how it’s quoted there. One of the differences that that makes is that if I were to say put X times 3, if X were the number 14, it would print 42, 14 times 3. But because it’s the character 1 4, multiplication means duplication so what I get is 1 4 1 4 1 4.
There’s a compare function that you can use to compare two strings, it’s a less than sign and equal sign and then a greater than sign and it returns a negative number if the first is less than the second, lower than the second. It returns a zero if they’re equal and a positive number if the first is greater. So, it’s like the compare or compared to functions.
IronRuby also has all the standard functions that you expect to do string manipulation with, including changing case, finding sub strings, formatting, justifying all of that so I’m not going to cover all of those. You can check the documentation for whatever function you need but I’ll just show you one real quickly for example. I’m going to assign X back to hello and then I’ll print out X up case and you’ll see in all capitals. Because the up case function takes no parameters. Remember, I don’t need to use parentheses after it, not even empty ones but it would be okay if I did.
Any object in Ruby can be tested for it’s truth value. Ruby has key words, faults and nil that have a truth value of faults and everything else is considered true, including zero and the empty string. The values true, false and nil, all these words are lowercase, can be assigned to variables, return from functions or methods and compared including expressions. You can also use the logical operators, and, or and not, all lowercase strings with booleans and they behave the standard way. So if you said X was true and Y was false, and then you said if X and Y put yes else put no, then, of course it would say no because they’re not both true. Now these operators use short circuit logic. So if there are two conditions joined by or or and, then the second condition won’t always be checked. Not unless it needs to be. In other words ‘and’ always behaves like ‘and also’ in Visual Basic and ‘or always’ behaves like ‘or else’. So, for example, suppose I were to say ‘if not why’ or ‘and then,’ I’ll have a little function here, put S$X and I say print yes and I say ‘and’ and it is going to print ‘yes.’ And the reason is that Y was false so ‘not Y’ was true.
Well, as soon as IronRuby saw that that first condition was true, it didn’t bother to look at the second one, it just immediately printed yes. But if I changed it and took out the not, and recreated the rest of the loop here, then because Yis false, it has to check that second condition. When it checks that second condition, it first has to perform that function. And so it puts out, it prints the value in $X which is true so you can see that it printed the word true but then, it checks the truth value of that put SX which is return value from the function, and the return value from put S$X, we’ve used it several times, so you probably have noticed that it’s nil. So, $Y is false and the return value from put SX is nil, both of those are false so it doesn’t print yes, it prints true but not yes.
Syntax Basics Demo
This little program that I’ve already written up as a script, covers some of the basics and a few new things. First of all, I’m defining a function called ask that has three parameters, here they are, a, comma separated and these two have default values so when the function is called, three values are not sent to as parameters then the default values will be used. Then we have a ‘while true’ loop here and we’re going to print out whatever was passed into be the prompt. Then we use this get s function that we haven’t seen before. It gets user input and assigns to ans. Then here’s another function we haven’t seen before, the chomp function. When the user input is taken in, it’s taken in as a string and it includes the enter that the user pressed at the end of their input. So that’s attached to the string that’s passed back in as a new line. What chomp does is it removes that new line so now we have the answer without the new line then down case, of course is a like up case, it moves it into lowercase. Then we check to see if what’s an answer is either no or end, if so we return false from the whole function or if it’s yes or Y in that case we return true.
If the user did not type in either no or yes or N or Y, then we decrement the number of retries left for them by default that 3, check to see if they’re out of retries, in which case we return false. If you can’t say yes or no, then we’re just going to make it no. And then, if they have yet used up all their retries, we will print out on the screen this reminder, enter yes or no, give then 3 chances. That’s the end of function definition here. So the rest of this script here uses it so it says if and we say ask as our prompt we’re passing in, ‘do you want to continue’ and we are changing the default number of retries to 2. If the result of this, ‘do you want to continue’ is true, which means they answered yes, then we’ll print continuing, otherwise we’ll print stopping.
So, let’s do that. I have to go to a DOS prompt so I’ll get out and I will type in IR and the name of the script that I want to run, got to have the extension on it, that RB has to be there. Let’s get it wrong here, and yes, it does say enter yes or no which is what we expected it to do and it’s giving me another chance so this time I’ll say yes, I do and it printed ‘continuing.’ If I answer ‘no’ instead, it prints ‘stopping.’ So we’ve tested it and it works.
Objects
Now let’s talk about object orientation. What makes IronRuby different from regular Ruby is the fact that it can use name spaces from the .NET libraries just as though they were native libraries. The keyword that you use for this is require which is like imports in Visual Basic. So, let me show you a script that shows how you import the core library and the system name space. Now the reason I’ve prewritten this as script is as you can see, although it’s easy to say require MS core lib, writing out these required is a lot harder because you have to have the fully qualified assembly name. But once you’ve done that, then you can use the classes that are in those assemblies so here, I’m using console.
I’m going to use the right line method and you can see that the console class, that looks the same but notice that instead of system. console, we have system colon colon. That’s the scoping operator there and then instead of the way you’re used to seeing right line written, we have the method name in lowercase, all lowercase and with an underscore between the two words so it’s just set up differently. This is the standard and you’re going to see it all through IronRuby when IronRuby is interoperating with .NET. So, this will write on the screen “hello, I’m Ruby from .NET.”
Then let’s say we want to use another class, a class that needs to be instantiated. This is system collection and here’s our double colons for the operators. And we’re going to use the Hashtable class so to instantiate it, we say Hashtable.new and that instantiates it as a Hashtable and we’re assigning it to this variable H. And then, with the variable H, we can use methods from the Hashtable. Here’s the ad method lowercase and we’re adding a key value pair, well two key value pairs. We can also use the contains key method, here it is, sorry. Here it is and it’s going to search for a particular key and if it finds it, just print found it.
,p>Now this shows you, this is a really good example of why people like to use dynamic scripting languages. This is so easy, you just say if E and H put as the key plus a space plus the value, you can’t get any easier that this. E knows how to instantiate itself to the correct type so that it has key and value properties. You have to do almost nothing, it’s simple and intuitive and quick to do. Now, I should mention, oh, let me run this first, so let me get back to my prompt here. I haven’t run it yet. And it’s going to print out “hello from hello IronRuby from .NET.” It prints out found it and it prints out both the values and our little Hashtable.
Now I want to also tell you that IronRuby has a Hashtable of its own and it’s also very easy to set up and use because that’s what dynamic languages are supposed to be, easy to set and use. So to do it, I’m going to say MyHash equals got a curly here, the key value and then what’s called the big error notation to show that key value points to, excuse me, that that key points to that value. Another one, and actually as many as we want, I suppose, close with the curly, and now I have declared a hash. And now I can use it. So I could say MyHash, put s, MyHash and in square brackets after it, the particular key that I’m looking for. Notice that I used curly brackets when I declared it but when I got a value by key, when I use the key to find a particular value, I used square brackets.
Now let me show you another example of interacting with .NET. This time I’m going to use an XML, the XML name space. And after I have required it, I’m going to create an alias for it just to reduce the amount of typing I have to do. So over here, when I want to instantiate a new XML document out of this system, XML name space, I can just use XML to prefix it. Now I have a document here in D and I’ll call the load method to load up the file called demo XML, let me show you what that file looks like. It’s just a little, a very tiny little file of names.
So, I’m going to use the select nodes method of the XML document. Again, all lowercase and with an underscore between the words to select the name nodes and I’ll put them here in N. So N is a collection of name nodes and I’m going to use my simple little loop to iterate through it. For E in N, I’m going to put E last child inner text. Let’s see if that works, again, I’m going to have to go back to my basic command line, don’t want to be inside IronRuby. And then I will call IronRuby and ask it to run my script for me and there’s the output.
In addition to interacting with classes that are in the .NET name space, IronRuby can also interact with classes you write yourself. So here’s a little simple class that I wrote, a very simple, it has 1 function called Say Hello and it returns to low and the name of it is Simple Class.
I’ve already compiled that class to a dll so that I can use it and it’s real simple so I’m going to just use in interactively. I’ll say require the dll, which is called simple class library.dll and then I’m going to assign to a variable from the simple class library name space the simple class and I’m instantiating it so, I’m saying simpleclass. new and then all I have to do is use my variable to call the say hello method and it should return “hello” and there it is.
You can also write your own classes in IronRuby. Here’s a simple example. Class, MyClass, there’s our class definition and then this method that we’re defining here called Initialize is the constructor for the class. The at sign in front of myVal shows that that is a class attribute, an instance variable. And it’s created by being set inside the constructor. Here’s what getters and setters for properties look like. This step here, MyVal named MyVal will get the private instance information. And the one called myVal= will set it. Then I’ve also included a regular method called double value, pass (n) into it and it returns the double event. Now to use it, the class itself could be part of another script. it could just be defined in that script and then used in that script. It wouldn’t necessarily have to in a separate file but it might be in a separate file if you want to make it available to a bunch of script, if it has some sort of functionality that can be used by different scripts.
So, if it’s in a separate file, then that file either has to be in the path so that the scripts that want to use it can find it or inside the script you could provide a path. So, I’m going to put REQUIRE here. I’ll just do interactively, MyClass, now that’s the name of the file, right, it’s showing, I’m doing this mostly to show how you put the path in there and you see that you need to use the double slashes. We’ve got the $ X equals and we’re going to instantiate the class MyClass. And now, I can use that MyVal property so is say $xmyval equals 8 and then I can print out MyVal and it prints the 8. And I can also use the more standard method and pass some value into be doubled and that worked also.
Got one more example for you and this one’s going to use WinForms. Now another video in this series, the one called Fundamentals of the DLR, also talks about using IronRuby to create Winforms and WPF Windows Presentation Foundation. And it has more examples but for now, we’ll look at this simple one here. I’m requiring the core library and the WinForms and the drawing. Then, I’m setting up a bunch of aliases because I’m going to use applications, forms, message box, button and point and I don’t want to have to type all this log strings in.
Okay, so here, class MyForm, this little arrow that points to the left says that MyForm inherits from form. In my constructor right here, I’m going to set a title, a text here for the form for self. And here I’m going to instantiate a button, give it a location and a text, a caption. Then I’m going to declare or define, excuse me, a method that is a click handler called MyClickHandler, it’s a handler method. It’s going to create – this is a code block right here and this code block is what will be executed when my handler is called. And inside it, this stuff inside the square, excuse me, inside the pipes, is the parameters that will be passed into it, the first is, of course, the sender and the second is the event args, just as you would expect. The actual code to be executed is, it will just pop up a message box that says “hello from Ruby.”
Now that click handler has to be attached to the button click method and this is how you do that. We take our button variable to it’s click method. We put in it’s click method, we’re assigning a reference to MyClickHandler so this is kind of just cookbook, just set it up like this, then we’ll add a button, this button to the collection of controls that are on the form. That’s basically the end of the form, excuse me, of the class definition for the form, then in the rest of the script, what we’ll do is we’ll instantiate this form to a variable called MyForm. And then we’ll pass that MyForm to the run method of the application so that it will start the form when the application runs. So now I’m going to go back to the command line and I’m going to run this. MyWinForm class when it – there it is, so here’s my form, it’s got my NET form from Ruby as it’s titled here and it’s got a click me button and when I click it, it says “Hello from Ruby.”
IronRuby and .NET Demo
So here’s a demo on the .NET interoperability with IronRuby. You’re probably familiar with Twitter, the website that let’s you broadcast or read tweets, little short messages. And you may also know about the Twitter timeline that shows you messages that are available generally to the public. Well, this demo shows using .NET interop to download the timeline as XML and then use the Microsoft Speech Synthesizer to read it out loud.
So, here we have requires for the system speech, to get the speech synthesizer and system XML.We’re going to instantiate a web client and then use that web client’s download string method to grab the content of this XML file which is available on the Twitter site. You can go look at it if you’d like. We’re storing it here in the content, then we create a new XML document and we also instantiate a speech synthesizer. Now, the XML document that we’re going to load up with that content, with the XML from Twitter and then we’re going to select the statuses nodes and with that collection of status nodes, we’re going to iterate through it for each status and for each one, we’re going to build some more XML because we need to create the format that the speech synthesizer expects. See how we’re using some speak tags here, I won’t go through all that format but the important thing is that we are picking up the inner text of the thing we downloaded and reformatting it so the synthesizer can use it. Then we’re going to print out whatever is there on the screen so you’ll see it printed when you hear it read as well. And then we pass to the speech synthesizer and that’s all we need to do. We’re ready to run it...
Reuters Japan business sentiment dives; BOJ sees more pain: Tokyo (Reuters) Japanese business senti ://tinyurl.com/ 5lh7.dt just got word that our dog died. Side note using
Okay, that’s enough. It just gives you an idea of what’s going on there, so I used CTRL-C to interrupt it, sort of random information but it’s an interesting demo.
Data
Working with files is mostly just cookbook, you can work directly in IronRuby like this. It has an open method of a file class. Let me show you quickly what that file looks like. Here it is, it’s just two lines, “Hello world.” The method here called each ine will automatically read each line and it will execute this code block. Here’s those curlies again and remember that what’s inside the bars is parameters that are being passed to this code block. So that’s going to hold the line that’s just been read in. So, I’m going to take that and chomp it. Remember that chomp means remove the new line and then, I’ll just print it out and I’m done. And I forgot to put the put s there, didn’t I? Let’s try again here. There, that looks better.
If you’d rather you can use the .NET classes that you might like because you’re more familiar with them or for some other reason so let’s do that. I’ll just do it interactively here. First I’ll require mscorelib and then I’ll create myself a stream reader SR by taking system IO file and doing the open text method to open that same file, test.text. Then I’ll set up a variable L and that variable is going to be used to hold each line as I read through. And so I’ll say while L is not nil, remember nil means nothing then we’ll read into it. And we’ll print it out what we read in. I did again. Let’s try one more time. There, so it read, it had already read the hello, I should have reopened it. Sorry. But basically, it read it and it read all the way to the end including the nil, I should probably have put in the conditional also, to keep it from doing that. But you see that using those .NET classes is very straightforward, you’re using them just the way you would in .NET, just little bits of the syntax are different.
Now, let’s look at exception handling. It should be familiar in its structure but it uses different labels so we’ll look at those. First of all, I have an app here that’s pretty much the same thing I just did a minute ago. Here’s the instantiate a stream reader and in a loop read into a variable and then print that variable out. But it’s going to break because the text file I told it to open doesn’t exist. It’s a typo here. So, I want to put this inside a try loop, I’m sorry, a try block, so this is what a try block looks like. It starts with began and ends with end. So in a sense begin is the try, and here’s everything we’re doing. By the way, I did start the stream reader, the SR variable here as nil, you’ll see in a minute why. And then here the catch block is called rescue and in this catch blocks, I’m just going to print out an error message.
And then in the final e block is called ensure, as in ensure that this gets done, no matter – in other words whether there’s an error or not, ensure that it happens. And what we’re doing inside the insurer is to close the stream reader if it was opened. Now we set it equal to nil so this will be false if it never got opened and if this is false, then of course, it won’t try to close it. But if there is something in it that means it was opened and will close it. So that’s that compact sort of backwards form of If being used real effectively here. Now let’s run it and see if it tells us there’s a problem which is what it should do. Too long a name and it told us there was a problem with the file so we’re happy cause that’s what we wanted it to do.
Accessing a database is also pretty cookbook, pretty straightforward. You’ll need to import the appropriate classes, so I’ve pre-written a script here. We’re importing system data along with system and mscorlib. And here’s our class that’s going to do it, it has only one function defined here, GetData. We set up a sequel string that has our query, select start from customers. We have a connection string that connects to the specific database that we need. We instantiate a data adapter, a SQL data adapter, here’s the news so we’re instantiating it and we pass it, both the SQL and the connection strings so that it can connect and execute that SQL.
We’re also going to instantiate a data set Then we’ll use the data adapter to fill the data set, now that the data set is full, we can iterate through it. Here we have two nested four loop for TN the collection of tables, there’s actually only one table in this data set but this could iterate through more than one. And then for each collection of rows, I’m sorry, for the collection of rows in that table, for each row, we’ll print out the first column, get items zero, the first column of that row. Then down here, we instantiate this class to the variable test. And then we call the get data method and so we get our data that way. Let’s see if it’s going to work for us. So, it’s going out now, it’s connecting to that database, and it’s going to return that first column and if you’re familiar with the Northwind database, then you can see that that’s exactly what’s in that first column.
Now, if what you’re doing is DML, instead of simple query, then you’ll just use the commands appropriate for that. Again, it’s the same as .NET logically and you use the same objects, you just change the syntax a little for the IronRuby.
Data Access Demo
Let’s look at one more database application. This time it’s Windows based, so we’ll have Windows Forms in drawing. We’ll declare a test database that inherits from Form. And in the initialized method in the constructor we’ll set a title for our form, we’ll set a size for it. Then we’ll create, we’ll instantiate a data grid view and we’ll give it a location, a size and we’ll add it to the collection of controls on this form. Here is our SQL connections string, excuse me, our SQL string, our query and our connection string. Here we’re instantiating the data adapter and instantiating a data set, filling the data set from the data adapter. All of that is just the same as we did a moment ago in the console. The only thing that’s different is in order to print it out, instead of looping through it, and printing it out, we’re going to, from that tables collection, get the first tables so the whole table and we’ll make it the data source of our data grid view so we will see a whole table. We’re going to run it. It connects to the database, brings down the whole table and there it is in a nice little data grid.
That’s the end of this introduction to the syntax of IronRuby with specific reference to how it’s similar to or different from VB. For more information here are links to sites that include the home sites for the Dynamic Language Runtime, the DLR and IronRuby. Those sites contain links that will lead you to other useful sites, including tutorials, examples and blogs.I also recommend that you search the web because IronRuby is a very new language and so right now, lots of new material is being written about it. I also want to remind you there’s more information on IronRuby in the fundamentals of the DLR Video which should be available from the same source where you got this video. It isn’t really a lower level session than this one, even though it’s called Fundamentals. It’s just less syntax oriented, so it covers a wider range of topics that I think you’re going to want to know about. Thanks for watching today. Bye, bye.
That’s the end of this introduction to the syntax of IronRuby with specific reference to how it’s similar to or different from DB. For more information here, [End of Audio]