Você está na página 1de 7

# 0.0 Introduction to Objects Everything is an object ======================= We will begin our journey with objects.

In Ruby, just like in real life, our world is filled with objects. Everything is an object - integers, characters, text, arrays - everything. To make things happen using Ruby, one always puts oneself in the place of an obj ect and then has conversations with other objects, telling them to do stuff. Roleplaying as an object in your program is an integral part of object-oriented programming. To know which object you are at the moment, one may use the keyword self. Try it for yourself: Example Code: self As you can see, if you don't specify which object you are, you automatically pla y the role of the main object that Ruby provides us by default. We'll delve into how one can play the role of different objects and why this is useful a little further down the line. Talking to objects ================== One object interacts with another by using what are called methods. More specifi cally, one object "calls or invokes the methods" of another object. In the example below, we call the method even? on the object that is the number 2 by placing a period (.) after the object, then adding in the name of the metho d we want to invoke. Example Code: 2.even? Invoking a method on an object inevitably generates a response. This response is always another object. Calling the method next on the object 1 has it give us t he next consecutive value, 2. One may also chain method invocations by simply adding more periods and method n ames sequentially - each method in the chain is called on the result of the prev ious method. Go on and try it by invoking next twice on 1 to get 3. 1 ``` Solution: 1.next.next ``` The results you're looking at are the consequence of running a series of tests a gainst your input to validate it. If you see results coloured red, this means on e or more tests failed. Green means you're good to go. # 0.1 More Objects and Methods

Looking up methods ================== Ruby objects are happy to tell you what methods they provide. You simply call th e methods method on them. Example Code: 1.methods As you can see, you get a listing of all the methods on the number 1 that you co uld invoke. The names are prefixed with a colon (:) that you can safely ignore f or now. If you find the results too muddled, you can easily sort them alphabetic ally. Try it for yourself - simply call the method sort on the result of methods : 1.methods ``` Solution: 1.methods.sort ``` Invoking methods with arguments =============================== When talking to an object via its methods, it is possible to give it additional information so it can give you an appropriate response. This additional information is called the "arguments to a method." The name "arg ument" makes sense if you stop to think about the fact that methods are the path s of communication between objects. Here's an example of an argument to the method index, which finds the position o f the argument in the array: Example Code: ['rock','paper','scissors'].index('paper') Here, index is the method and 'paper' the argument. If there is more than one ar gument, they can be passed to the method by simply separating them with commas. Try using a method that takes two arguments - use the between? method to determi ne if the number 2 lies between the numbers 1 and 3. 2 ``` Solution: 2.between?(1, 3) or 2.between? 1, 3 ``` # 0.2 Syntactic Sugar for Special Methods Special Methods =============== As an observant initiate, you've probably noticed that in the last lesson, Integ er objects list mathematical operators like + and - among their methods. You pro bably also thought to yourself that invoking the + method like so - 1.+(2) - to add two numbers would be... clumsy.

It is, though it works just fine - try for yourself by adding 4 to 3 in the exer cise below. ``` 4.+(3) ``` Ruby as a language aims to be extremely programmer-friendly, so you can usually safely assume that there is a better way. Ruby makes an exception in its syntact ic rules for commonly used operators so you don't have to use periods to invoke them on objects. Let us rephrase the previous example in a more natural syntax by omitting the pe riods and brackets. Example Code: 1+2 # this is same as 1.+(2) There are several other method names that have this special status - here's a qu ick summary of the ones you're most likely to run into. + * / = == != > < >= <= []

This last method ([]) you've probably already seen in the lesson that covers Arr ays, and is arguably the most unique in its syntax. Not only does it not require a period, it also encloses the arguments to itself. Here's a quick example to r efresh your memory: Example Code: words = ["foo", "bar", "baz"] words[1] Even more interesting is that it still works if you use the more traditional met hod syntax - see for yourself by running the example below. Example Code: words = ["foo", "bar", "baz"] words.[](1) This is a common pattern in Ruby - two different ways to do the same thing where one remains consistent and the other changes the syntax to be more programmer f riendly. # 1.0 Introduction to Strings String construction =================== In doing lies the true path, so let us begin by doing. Type out "Ruby Monk" in t he box below (remember to include the quotes). "Ruby Monk" Strings are key to communicating with a user and programming apprentices will en counter and start manipulating strings from the earliest stages of their journey . In this lesson, we will explore some of the tools Ruby provides to create and manipulate strings. Literal forms

String construction has what is known as a literal form - the interpreter treats anything surrounded with single quotes (') or double quotes(") as a string. In other words, both 'RubyMonk' and "RubyMonk" will create instances of strings. It's your turn now; go ahead and create a string that contains the name of the c urrent month. Like, 'April', or 'December'. 'June' Action etches deeper into the memory than mere words. Recreate the string in the exercise above using double quotes ("). You'll see that the tests pass the same way as they did before. "June" The single quoted and double quoted approaches have some differences, which we w ill look into later. For most purposes they are equivalent. All Strings are instances of the Ruby String class which provides a number of me thods to manipulate the string. Now that you have successfully mastered creating strings let's take a look at some of the most commonly used methods. String Length As a programmer, one of the common things you need to know about a String is its length. Instead of merely telling you how to do this, let me share a secret abo ut the Ruby API with you: Try the obvious! The Ruby core libraries are very intu itive, and with a little practice you can effortlessly convert instructions in p lain English to Ruby. Test your intuition and try to change the code below to return the length of the string 'RubyMonk'. 'RubyMonk'.length That shouldn't have taxed your intuition too much! Let's move on to slightly mor e complex concepts. # 1.1 String Basics String Interpolation ==================== It is essential to be able to replace placeholders within a string with values t hey represent. In the programming paradigm, this is called "string interpolation ". In Ruby, string interpolation is extremely easy. Feel free to run the example below to see the sample in action. Example Code: a = 1 b = 4 puts "The number #{a} is less than #{b}" Do remember that placeholders aren't just variables. Any valid block of Ruby cod e you place inside #{} will be evaluated and inserted at that location. Isn't th at very neat? Now let us see you wield this tool. Complete the functionality of the method bel ow which, given a String as the argument, inserts the length of that String into

another String: def string_length_interpolater(incoming_string) "The string you just gave me has a length of #{incoming_string.length}" end We've been using double quotes in all our string interpolation examples. A Strin g literal created with single quotes does not support interpolation. The essential difference between using single or double quotes is that double qu otes allow for escape sequences while single quotes do not. What you saw above i s one such example. \n is interpreted as a new line and appears as a new line when ren dered to the user, whereas '\n' displays the actual escape sequence to the user. Let us move on... Search in a String ================== Another common scenario is checking if a String contains any given character, wo rd or sub-string. Considering your experience with the Ruby API and its intuitiv eness, try and check whether the String given below includes 'Yoda'. "[Luke:] I can t believe it. [Yoda:] That is why you fail.".include?('Yoda')

Did you manage to figure that out by yourself? Too many cooks spoil the broth wh ile too many hints lead the hunter astray! Now check if the string below starts with 'Ruby'. "Ruby is a beautiful language".starts_with?"Ruby" After that, checking whether the statement below ends with 'Ruby' should be easy . "I can't work with any other language but Ruby".ends_with?"Ruby" Are you getting the hang of the Ruby API? The previous three methods all ended w ith a '?'. It is conventional in Ruby to have '?' at the end of the method if th at method returns only boolean values. Though it is not mandated by the syntax, this practice is highly recommended as it increases the readability of code. Sometimes we will be required to know the index of a particular character or a s ub-string in a given String and conveniently Ruby provides a method on String th at does exactly that. Try and find out the index of 'R' in the string below: "I am a Rubyist".index('R') String case change ================== The last thing we will look into in this lesson is manipulating the case of stri ngs. Ruby provides us with a convenient tool-set to take care of proper and cons istent casing within strings. Let's start with converting a string in lower case to upper case. Example Code: puts 'i am in lowercase'.upcase #=> 'I AM IN LOWERCASE' Similarly, one can convert a string to lower case as well. Ruby calls this metho d downcase. Convert the string below into lower case.

'This is Mixed CASE'.downcase On a parting note, let us touch on an interesting method. When you encounter a m ixed cased string, Ruby provides a way to swap the case of every character in it i.e. this method would convert "I Am MixEd" to "i aM mIXeD". Try to figure this method out and tell us if you ever come across a scenario where you find use fo r this. It might make a good story for a rainy night! "ThiS iS A vErY ComPlEx SenTeNcE".swapcase # 1.2 Advanced String Operations Splitting Strings ================= In this lesson, we will have a look at some vital methods that the String object provides for string manipulation. Splitting strings on a particular word, escape character or white space to get a n array of sub-strings, is an oft-used technique. The method the Ruby String API provides for this is String#split. Let us begin by splitting the string below o n space ' ' to get a collection of words in the string. 'Fear is the path to the dark side'.split(' ') One can effectively manipulate strings by combining String#split and a Regular E xpressions. We will take look at Regular expressions, their form and usage furth er down the lesson. It is possible to similarly split strings on new lines, and parse large amounts of data that is in the form of CSV. Concatenating Strings ===================== You can create a new string by adding two strings together in Ruby, just like mo st other languages. Example Code: 'Ruby' + 'Monk' Ruby often provides more than one way to do the same thing. The literal and expr essive method for String concatenation is String#concat. Example Code: "Ruby".concat("Monk") Let's try a more widely used alias. You can use '<<' just like '+', but in this case the String object 'Monk' will be appended to the object represented by 'Rub y' itself. In the first case of using '+', the original string is not modified, as a third string 'RubyMonk' is created. This can make a huge difference in your memory utilization, if you are doing really large scale string manipulations. C hange the code above to use '<<' and see all the tests passing again. Replacing a substring ===================== The Ruby String API provides strong support for searching and replacing within s trings. We can search for sub-strings or use Regex. Let us first try our hands a t something simple. This is how we would replace 'I' with 'We' in a given string : Example Code:

"I should look into your problem when I get time".sub('I','We') The method above only replaced the first occurrence of the term we were looking for. In order to replace all occurrences we can use a method called gsub which h as a global scope. Example Code: "I should look into your problem when I get time".gsub('I','We') If you haven't come across the term Regular Expression before, now is the time f or introductions. Regular Expressions or RegExs are a concise and flexible means for "matching" particular characters, words, or patterns of characters. In Ruby you specify a RegEx by putting it between a pair of forward slashes (/). Now le t's look at an example that replaces all the vowels with the number 1: Example Code: 'RubyMonk'.gsub(/[aeiou]/,'1') Could you replace all the characters in capital case with number '0' in the foll owing problem? 'RubyMonk Is Pretty Brilliant' Find a substring using RegEx ============================ We covered the art of finding the position of a substring in a previous lesson, but how do we handle those cases where we don't know exactly what we are looking for? That's where Regular Expressions come in handy. The String#match method co nverts a pattern to a Regexp (if it isn t already one), and then invokes its match m ethod on the target String object. Here is how you find the characters from a St ring which are next to a whitespace: Example Code: 'RubyMonk Is Pretty Brilliant'.match(/ ./) As you can see in the output, the method just returns the first match rather tha n all the matches. In order to find further matches, we can pass a second argume nt to the match method. When the second parameter is present, it specifies the p osition in the string to begin the search. Let's find the second character in th e string 'RubyMonk Is Pretty Brilliant' preceded by a space, which should be 'P' . 'RubyMonk Is Pretty Brilliant'.match(/ ./, '9') All the complex use cases of this method involve more advanced Regular Expressio ns, which are outside the context of this lesson. However, on an ending note, if you ever choose to implement a parser, String#match might turn out to be a very good friend!

Você também pode gostar