Ruby Trick Shots: 24 Ruby Language Tips and Tricks

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi I'm Peter Cooper and I'm going to show you lots of quick fire Ruby trick shots why the picture of the boxcar I was originally going to do this as a collection of stunts that graphic work better for that but I like the graphic so I'm going to keep it now trick shots a small Ruby tricks or techniques that I've seen or shared experience in various ways and that very experience rubyists that I know have said I didn't know that all wow that was kind of cool so if an experienced rubyist has actually said that a technique I keep it note it down and I think it's worth saving to share so I've got just over a hundred of them now and I'm going to share about twenty to twenty-five in this video but the plan is for the full collection to be put into an e-book and online into regular HTML pages with some explanatory text that goes into you know why this occurs how am I going to do this do you think this is a big money-making scheme well no it's actually going to be free but part of the reason for doing this is that I want to test the concept of cheap fun Pro going related books that you can just sit and read anywhere on the couch the bus whatever on the Kindle as I haven't seen any yet and I think it could work so it will cost a few dollars on the Kindle but that will be it but it's all going to be on the web too so you'll get that bit for free or you can just watch this video and enjoy this so let's give you some warnings first first I'm using my ruby 1.9.3 if you're using JRuby rubinius something else some of the tricks may not work perhaps on one point eight even at most will because they're related to Ruby's core syntax secondly not every trick should be used in production code and what I mean by this is not that they're necessarily dangerous but that they're perhaps a little bit too clever sometimes and if you use the normal of your code examples everywhere people might you know they might not be very cool with that so most of fine and some may even give you a Wow I must use this moment and I've had people come up to me after a talk that I gave like this people say I'm going to use that technique but some will just make your code look bad and air quotes too clever so be careful so before we get to the tricks if you like what you see there should be a box further down on this page unless you're on YouTube unfortunately with an email signup so you can get a few emails about the release of the book so it's not gonna be any spam anything like that and because my mail provider MailChimp they would Massacre me if I pound you so you're safe and every email gets in them it has immediate unsubscribe links at the bottom too so you immediately get out of it if you don't like it for whatever reason so without further ado on to the trick shots getting a random number in Ruby is quite easy we use the random effort here very simple ran 10 that'll give us number between 0 & 9 but what if we want to get site from a range well sometimes you might have a high number you want to get a low number and then you'll do some kind of magic where you do high - the low plus the low or that type of thing well in ruby 1.9.3 we no longer need to do this we can use Rand and we can literally use a range in there and that will even work with the non-inclusive ranges now if you're on 1.9 point - that's not going to work but there is a kind of a workaround for it you can use random new Rand I know and that will work in exactly the same way I'm one mine too so let's hope this becomes popular technique soon because it really does save a little bit of the full process on time most rubyists frequently have a need to get a nicer representation of their objects dig into them for the debugging that type of thing and you might be used to using P so like that or PP which is a prettier version but awesome print is an even prettier version let me just show you so what I'm going to do is require AP I'll put in that same array you can see where the index numbers and it's colored all that type of thing now if I go to some code here we have an array of hashes and there's also some kind of internal embedded arrays in there as well I'm doing exactly the same thing as before if I head back to the prompt however and I actually run this code you get to see it's all coloured it's all indented all that type of thing so really really cool I think it's best you know oh let me just tell you that the name of the gem is Wilson print it's not just a P but you should Google awesome underscore print go to the github page and learn more about it because I've just shown you the very basics even integrates with active record there's a way to make it be the default output form in IRB or pry lots of stuff to learn so excellent work there for Michael Dvorkin and definitely one of my recommended libraries this one really is curious let's say we want to concatenate one string to another well some people may consider this to be concatenation but there is also this that's nice and simple the good thing about using concat is it will actually return exactly the same object it takes the ABC string and then puts the EF into it but it's exactly the same object the same object ID everything but there's another way of doing this try this or now what's going on here you might not see any methods or anything going on just merely having spaces in between multiple strings gets us them all concatenated together if I come over to this you may think okay what's happening is it using class or is it using concat behind the scenes to do all of this the answer is no if we run this code what I've done here is I've overridden what plus and concat do in the string class could learn this a bit more tidy but you know nice and quick and scrappy if I run this we get the exclamation marks for the using the plus method but we still get ABC back by using this technique so it's circumvents all of that it's a more direct way of concatenated string together interesting curiosity let's say you want to call a function a system library or some other library that's been compiled well you can do so out the box we've driven 1.9 using something called fiddle which is an abstraction for the FFI which is the foreign function interface so all we do is we bring fiddle into play we open up the Lib C which is the C standard library this is the file name that it has on Mac OS 10 and then we create this basically the function object that points in to the string length that's part of the C and we tell it we going to pass in a void pointer and we expect back an integer we make the call on this little string and we would get back the number 5 but you may be more familiar with using a library called FF I directly and we can do that and you might even prefer this API C or works in a very similar way but just as a different way of calling and setting up the function handler well the difference is is that for FF I you have to do a gem install FF I to get out of it whereas fiddle is part of the standard library in Ruby but is there a better useful of this than just getting the length for Strings we can already do that in Ruby anyway well the reason that I got into this was that a friend of mine was trying to reemployment the system crypt function so that's what I'm referring to here and I said why don't we just do it this way so this made it really nice and simple nice and quick and if we run this you get to see the cryptid output so I thought I'd let you know about that but you may want to use FF I instead this is the simplest way to check whether one string contains another as a substring so I've got my string here x equals this is a test and the most common way that I see people do this is they would do like a regular expression and put that together that way well it's actually a lot simpler than that just do that because if the string doesn't exist inside there so I'll pick that then we get nil back so you can use this even in a conditional very simple useless trick alert you may know there are many ways to put literal strings into Ruby so for example and do this type of thing but then there's also these approaches using the percent sign which can be very handy and you can use a lot of different things as delimiters the number of special characters that you can use well believe it or not you can actually use spaces so try this on for size that actually works evil don't use it but it's a trick certainly this isn't time to give you an introduction to exactly what modules are but hopefully you're familiar with this type of construction where we have two modules food and food to which both have a method inside and we include those into a class and then we try and use that method what's happening here well when we include foo that goes on to the ancestor chain when we go through - that actually ends up underneath - on the ancestor chain so it's version of bar will end up being called first well what happens if we want to include multiple modules in a different way you can actually put on the same line so look at this line here for example I've done include a B C well what happens well what I've done is I've gone in I've used the included method on the modules just to see when they get included so what I'm going to do is I'm going to run that and you'll see it goes C B a so that's the order that they're being bought into play so very interesting but you may get confused by the ordering of this here but a lot of people didn't seem to realize when this someone posted this on Twitter that you can actually do this with include so you may find it useful string interpolation in Ruby is very simple we have two strings here one on instance variable called maestra one on a local variable called maestra different strings however now you may be familiar with if I want to print out the value of the string I could put in some rubbish here I can use pound sign curly braces and then I can include whatever I like in here including for any Ruby code in fact interpolation well if you are using instance variables or actually any variable that has a sigil at the start so that's the the act symbol or the dollar symbol for doing global instance and class variables you actually don't need the curly braces you can just do it like this and that works straight out the box [Music] if you want to check that a ruby source code file is syntactically valid you can do so directly from the command prompt just use Ruby - C and then your file name and it will tell you whether the syntax is okay or whether it's not now this won't tell you if there's going to be an exception as soon as you run the code and it may pass okay you may put method names in that don't even exist but it's all about the syntax and I just like to thank Nick curanto for letting me know about this tip in the last trick we merely checked whether a ruby source file had valid syntax or not well we can go a step further with Ripper that comes with 1.9 it's in the standard library what we can do is we can do syntax analysis we can see how ruby has interpreted a piece of code what does it actually mean and a piece of code that's actually quite interesting it's quite confusing is what does puts curly braces class put out well it doesn't tell you that it's a hash and there's actually some more complexities to this so all you do is you - require Ripper I'm using awesome print as we mentioned before because the output from Ripper is quite complex very complex these syntax trees and then I use s exp so what that would do is it will show us the syntax tree in an S expression so I'm going to not run this from here I'll run this from the command prompt run Ruby Ripper and this is quite complex you do get used to reading these eventually so you get to learn and that you know you get to look at calls and then where the method name is and all this type of stuff up here and these are quite tricky to read but once you get the hang of it you'll eventually start to go through and you'll realize what each of the different parts means and why a certain output occurs and in this case when we're doing puts curly braces dot class that curly brace is actually representing a code block as being passed to puts and then class is being called on the output of puts or the result of puts even which is nil did you know that you can chain ifs together some people didn't so that's why I've included it as a trick personally I don't think it's incredibly useful we'll just give you a very quick demonstration like so there you go quoting from O'Reilly the Ruby programming language the next statement causes a loop or iterator to end the current iteration and begin the next and we can see that in play here we go from 10 up to 20 using the up to you method we use next and that will skip all of the even numbers so we'll only print the odd ones as you can see here 11 13 so on if we move to map slightly different example but again we have a code block now something that that quote from the book didn't take into account is that this code block behind the scenes it's treated as a proc block you may be familiar with lambdas lambdas are just a slightly different flavor of prop block ever slightly from behavior now from a lambda what you can do is you can use the return statement like you would from a method but in a proc block things are slightly different if we use return here and I will try that we get unexpected return and that's because in prop blocks the scope of things like return it will come out to the outer scope it's not actually referring to the scope of the block itself now hopefully you know what this will do we're going to take our array and we're going to map that array to another one using the logic that's inside the block so what happens behind the scenes is that the map method will call this prop block each time for each element and then set the element to whatever the value is that's returned so 2 4 6 8 in this case well what if for some reason I want to just randomly let's say set the value to something else so I'll write this perhaps as I might logically think I could do it so let's say I want to return 10 if you know random 5 is equal to naught for example will that work well no it won't it will come up with that unexpected return error again but in the scope of prop blocks next is actually like its form of doing a return so this will return 10 to map and then map can put 10 into the array and off we go I'll actually reduce this number just to increase the odds of us actually seeing something a curb and I run this and you see so it would have been 2 4 6 8 but randomly ended up putting a 10 in here and that's all thanks to the next just be a few enjoyment I have a video on YouTube called the introduction to proxy lambdas and closures in Ruby it's about half an hour long and it digs into a lot more detail about this type of thing I thought this was pretty simple but I've actually seen a few advanced rubyists get called out by this one and say wow that's a really really cool trick so I want to show this off it's called array zip method on the array class so I've taken to erase here one of names one of Ages and I just do names doctor zip ages and it's it sums together so you end up with an array of arrays where each element has the name and the age of each respective index kind of zip together it because it will if you will now we can do something really cool with that we can use the wonderful hash square brackets method to form a hash from one of those zipped arrays so what happens in this case we actually end up with frayed fur CHS for seven and so on in a hash that can actually be quite useful but there's a little bit more to zip than this you don't just have to do it one thing to another if you look at this example here I've added something else called locations and you can actually zip the names to the ages and the location so end up with you know a slightly different arrangement here but then zip can also take a block and this pretty much works a bit like putting each on the end essentially just a little bit of a shortcut and gets you access to each zipped sub array as it were and then this just shows you what happens there short and sweet one this what if you want an array of the numbers of say 10 through 20 BAM there you go done how exactly this working well you can explode things into arrays in you know pretty much with any object that supports 2i so to convert something into an array kind of implicitly behind the scenes so for example what I could have is I could literally have just a number 10 floating around and I can get it into an array but then see may be an array well bear I can still get it into an array so this can be handy in same methods where you're being passed something you know if it's gonna be an array or some kind of object just a singular object and you want to loop over it well you can just force it into an array in this way and it works for everything there is actually a shortcut to doing this I say shortcut it takes longer to type but you may prefer the way this syntax works like so and again like so be careful with hashes though they don't behave in quite the same way be careful JSON or Jason is more commonly known JavaScript object notation it's very handy format for passing data around and even you know putting output from Ruby and you can do it very easily now because Jason comes in the standard library so what you do is just require Jason you want print stuff out in kind of like a P style form you know like what I've got here I've got an array of hashes and I can use P to print out the you know print out the Ruby object kind of notation there of it what if I want to do it as Jason I can just use J now that I've loaded the json library up looks exactly the same way and then this works could be copied pasted into javascript let's say there is also another extra part which is JJ and all that does is it kind of is the equivalent of PP really it's more like a pretty printing of that let's say you want to dynamically get hold of the name of the method that you're currently in you can do it with underscore underscore methods underscore underscore and the equivalent with call e in as well so you can see that in play here we call my method we're printing both of those out and we get a symbol with my underscore method inside I think why is this useful if I'm in my method I know I'm in my method well if you're doing meta programming there may be some reason why you know you don't actually know exactly where you are at that point so a slightly more complex example here bit convoluted but we're kind of dynamically generating methods called a B and C within this class then we call a B and C once they've been generated using defined method and because we got the underscore underscore method thing in here and again it could be call E if we run that we then get the symbols for a B and C back so it's a way for a method to check what its current name is I might not even need to say much for this one this is just a case of if you're doing method chaining you don't need to cram it all into one gigantic line or split things up into multiple different kind of expressions you can still do method chaining and split them across multiple lines you can see that in action here and a lot of people me included use IRB as a kind of glorified calculator from time to time well one thing that coming very handy there is knowing that underscore as a variable refers to the last return value that occurred you know lb so for example give you very very quick example a times to underscore will now continue to equals 20 and we can keep using that and again now underscore equals 400 so you can use that to build calculations up upon one another if you'd necessarily don't necessarily want to use variable names two tips in one here did you know that you can represent binary numbers in Ruby using zero B and then your binary representation of a number what you do now but what you can do in Ruby and you don't have to do this on binary numbers because they just turn into normal fixed numbers at the end of the day is you can check which bits are set within a number so in this case we'll keep it very simple so that we'll do that it's not 170 it's just literally not one not one not one so on well let's say we want to check whether the you know the first bit is set or not it's not and remember the indexing on a raise just be very careful there this isn't actually an array it looks like a ray indexing but we're actually checking whether a bit is set or not so this naught is checking is that set and then the one is checking is that set two would be there free would be there for with it and so on and so forth now there's another way of doing this this may be the more kind of like traditional way of doing it is you could also do C and then do a binary and with one shifted to the right number of places there here you wouldn't be checking for whether it's one or not though but just checking whether anything that's non zero comes back it is possible for method parameters to use other method parameters in their defaults so here we have a but then we have B equals a meaning that if B the second parameter doesn't come through the second argument isn't passed then that will default to whatever a was so here when we passing just one a and B both become 1 1 comma 2 we get a equals 1 B equals 2 Proc objects have a source location method this will return an array with the file name of the file where that proc object is defined and then the second element is the line number upon which is defined so here it's very simple if I run that you get eat the file name each time and then the line number on which defined I actually use this to quite good effect in a testing library I built called test rocket where you put assertions in different proc objects but this also works on methods as well so if we you know grab hold of will use awesome print which I mentioned earlier in the video and then I will grab that AP method that's been defined by it and then I'll ask it for its source location so if I run that we see this added on now way down deep in my file system on line 14 is where it's defined so this can be very useful for debugging but it's also for if you're building tools that are working with Ruby code and you want to dig into things I believe the pry there's like an alternative thing to IRB I believe that uses it to pull out the source code for things dynamically on the flight I also saw someone use this technique by in rails for example where you're checking to see what did active support stamp all over a monkey patch and the reason for that is that if you call source location on something that's an internal Ruby method that hasn't been messed with it will come back and it will be nil but if you do it on something that has been messed with and I must admit this isn't the best demonstration but if you call it on something else so I take where it's you know added an extra method to the string class table eyes and I run source location then it will tell us somewhere way down in the file system where active support lives so it can be a way of checking for that as well let's say you want to prepend one string to another I've got world here well you know you could always do something along these lines and again we've put hello to the beginning there well that's not very efficient because what's happening is it's creating a new string object and things have to be garbage collected and so on and so forth so another efficient way of doing this and this is one that you may be actually be familiar with is we'll say insert a position 0 we insert the hello that way that returns the same object that time much more efficient but in really 1.9.3 there is actually a prepend method that does exactly the same thing see anything unusual about this source code here well it's this underscore underscore end underscore underscore what that does is tells Ruby don't go beyond this point treat everything beyond this point as data essentially so I run this we only ever get hello well because it will never actually move on past that end point here but why is this useful well ruby has this concept where it will create something that's a file object that points to the current file in data when you have this end tag present and what we can do is let's do put static read we run that and then we actually get that text that was down the bottom is now coming back so we reading it like it's a file it is a file source code file and we get that data out so you could store data that's associated with a small Ruby script in this way underneath the file there's one small quirk to this though that I know some people weren't familiar with all that's happening is is that data is pointing to the current file but it's seek position is place literally just after the end what this means is you can actually rewind the seek position and you could do you know print out data read if I change it to a puts because it looks nicer and if I run that you'll now see we actually get the entire source code file come out so this can be a way of reading the current file in it without using the underscore underscore file route last but not least I'm going to show you a few simple regular expression techniques these going to be very simple I'm actually doing a full Lemp kind of masterclass style video of the regular expressions in Ruby digging into optimizations and you know literally start to finish regular expressions but I'm just going to focus on a few things here so I've got my string Fred Flintstone superhero and what I'm going to do is I'm gonna start very very simple let's say you know I want to make make the first match of a group of one or more word characters well I can do that that gets me my Fred very simple you probably familiar with this type of thing but you know I can extend this a little bit more that gets me my Fred Flintstone but then because I've used parentheses here to kind of you know get some matches I can then ask it for the first match of an ask it for the second match again that's pretty cool pretty straightforward where it starts getting interesting is when you want to give names to these so what you can actually do in here is I'm going to call the first one I and second one be I don't have to be names as simple as that it could be like f name and L name or something along those lines but we'll keep with a and B very simple well now if you put a symbol in here that symbol will come up with the match instead and you don't even need to do all of that you can actually just do that and then you can still get access to this stuff using special variable which is called dollar tilde and this gives you access to the same thing I'm not big fan of this but if you're doing some pretty scrappy could be useful and then last but not least this little trick I showed this off at the talk and I was a little bit hesitant about whether this is a good idea or not but a guy came up to me afterwards and he says I'm going to be using this in my scripts like this is really useful thanks for letting me know so I have to include it it's a little funny kind of rubric work if you take the regular expression and it has to be literal on the line and at the start of the line use the operators to the match against the string you think okay what's happening there well it's just telling me that there was a match you know on the very first character which that's pretty obvious but what it's done is it's set and it's created the local variables of a and B containing that information inside so you may find that useful nice trick so that's it folks I hope you learnt a few interesting things from this whether you're interested in the book or not you know just use this video on its own if you like but otherwise sign up below if you're on YouTube you might have to kind of look at the URL and go to that URL that's on the page but if you're on the page that hopefully I've sent to you then you can sign up below you won't get any spam or anything like that I mentioned that at the start of the video sign up you'll learn about that when the Kindle book comes out also when I put these things on the webpage as well so yep just sign up that will be great fun but otherwise yeah thanks for watching I hope you enjoy some of the tricks and remember I've got like about four or five times more than this and I want to stretch them properly go into a little bit more explanation about them so you know be kind of fun but just remember the warnings I gave earlier you don't necessarily want to cram all of these into your production code so thanks for watching I'll talk to you soon
Info
Channel: Peter Cooper
Views: 51,467
Rating: undefined out of 5
Keywords: ruby, tips, tricks, programming, rubylang
Id: gIEMKOI_Y-4
Channel Id: undefined
Length: 27min 48sec (1668 seconds)
Published: Mon Feb 06 2012
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.