practice from RubyMonk

来源:互联网 发布:qq飞车抽奖辅助软件 编辑:程序博客网 时间:2024/05/22 16:42

[]You can create an array with a set of values by simply placing them inside [] like this: [1, 2, 3]. Try this out by creating an array with the numbers 1 through 5, inclusive.[1,2,3,4,5]Arrays in Ruby allow you to store any kind of objects in any combination with no restrictions on type. Thus, the literal array [1, 'one', 2, 'two'] mixes Integers and Strings and is perfectly valid.Looking up data in ArraysLooking up values within an array is easily done using an index. Like most languages, arrays in Ruby have indexes starting from 0. The example below demonstrates how to look up the third value in an array.[1, 2, 3, 4, 5, 6, 7][5]Go ahead on try it out - extract the last value from the array below.[1, 2, 3, 4, 5][-1]Growing arraysIn Ruby, the size of an array is not fixed. Also, any object of any type can be added to an array, not just numbers. How about appending the String "woot" to an array? Try using << - that's the 'append' function - to add it to the array below.[1, 2, 3, 4, 5]<<"woot"Unlike many other languages, you will always find multiple ways to perform the same action in Ruby. To append a new element to a given array, you can also use push method on an array. Add the string"woot" to given array by calling push.[1, 2, 3, 4, 5].push("woot")Using '<<' is the most common method to add an element to an Array. There are other ways as well, but we will touch upon them later.Transforming arraysNow on to more interesting things, but with a little tip from me first. Try running this:[1, 2, 3, 4, 5].map { |i| i + 1 }STDOUT:[2, 3, 4, 5, 6]You'll notice that the output, [2, 3, 4, 5, 6] is the result of applying the code inside the curly brace to every single element in the array. The result is an entirely new array containing the results. In Ruby, the method map is used to transform the contents of an array according to a specified set of rules defined inside the code block. Go on, you try it. Multiply every element in the array below by 3 to get[3, 6 .. 15].         [1,2,3,4,5].map { |i| i * 3 }STDOUT:[3, 6, 9, 12, 15]creates an array [3,6,9,12,15] for an input array of [1,2,3,4,5] ✔Ruby aliases the method Array#map to Array#collect; they can be used interchangeably.Filtering elements of an ArrayDeleting elementsOne of the reasons Ruby is so popular with developers is the intuitiveness of the API. Most of the time you can guess the method name which will perform the task you have in your mind. Try guessing the method you need to use to delete the element '5' from the array given below:[1,3,5,4,6,7].delete(5)I guess that was easy. What if you want to delete all the elements less than 4 from the given array. The example below does just that:[1,2,3,4,5,6,7,8,9].delete_if{|i| i%2==0}Iterationfor loops?Ruby, like most languages, has the all-time favourite for loop. Interestingly, nobody uses it much - but let's leave the alternatives for the next exercise. Here's how you use a for loop in Ruby. Just run the code below to print all the values in the array.array = [1, 2, 3, 4, 5]for i in array  puts iendOk, your turn now. Copy the values less than 4 in the array stored in the source variable into the array in the destination variable.def array_copy(destination)  source = [1, 2, 3, 4, 5]  for i in source     destination.push(i) if i < 4  end  destinationendlooping with eachIteration is one of the most commonly cited examples of the usage of _blocks_ in Ruby. The Array#eachmethod accepts a block to which each element of the array is passed in turn. You will find that forloops are hardly ever used in Ruby, and Array#each and its siblings are the de-facto standard. We'll go into the relative merits of using each over for loops a little later once you've had some time to get familiar with it. Let's look at an example that prints all the values in an array.array = [1, 2, 3, 4, 5]array.each do |i|  puts iendOk, now let's try the same thing we did with the for loop earlier - copy the values less than 4 in the array stored in the source variable to the array in the destination variable.def array_copy(destination)   source = [1, 2, 3, 4, 5]   source.select {|i| i < 4 }.each do |i|     destination.push(i)  end  destination endProblem StatementGiven an array containing some strings, return another array with their lengths, in the same order as they are.You are supposed to write a method named 'length_finder', which accepts an array and returns another array as described before.Example:Given ['Ruby','Rails','C42'] the method should return [4,5,3]#my answerdef length_finder(input_array)  out_array = []  input_array.each do |i|    out_array.push i.size  end  out_arrayend#答案def length_finder(input_array)  input_array.map {|element| element.length}endSplitting StringsIn 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 an 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 on space ' ' to get a collection of words in the string.'Fear is the path to the dark side'.splitSTDOUT:["Fear", "is", "the", "path", "to", "the", "dark", "side"]splits the string on space ✔One can effectively manipulate strings by combining String#split and a Regular Expressions. We will take look at Regular expressions, their form and usage further 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 StringsYou can create a new string by adding two strings together in Ruby, just like most other languages."Ruby".concat("Monk")'Ruby' + 'Monk'Let's try a more widely used alias. You can use '<<' just like '+', but in this case the String object 'Monk' will be concatenated to the 'Ruby' String itself. Change the code above to use '<<' and see all the tests passing again.Replacing a substringThe Ruby String API provides strong support for searching and replacing within strings. We can search for sub-strings or use Regex. Let us first try our hands at something simple. This is how we would replace 'I' with 'We' in a given string:"I should look into your problem when I get time".sub('I','We')STDOUT:We should look into your problem when I get timeThe method above only replaced the first occurrence of the searched for term. In order to replace all occurrences we can use a method called gsub with has a global scope."I should look into your problem when I get time".gsub('I','We')STDOUT:We should look into your problem when We get timeIf you haven't come across the term Regular Expression before, now is the time for 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 let's look at an example that replaces all the vowels with the number 1:'RubyMonk'.gsub(/[aeiou]/,'1')STDOUT:R1byM1nkCould you replace all the characters in capital case with number '0' in the following problem?'RubyMonk Is Pretty Brilliant'.gsub(/[A-Z]/, '0')Find a substring using RegExWe had earlier 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 handy. The String#match method converts a pattern to a Regexp (if it isn‘t already one), and then invokes its match method on the target String object. Here is how you find the characters from a String which are next to a whitespace:'RubyMonk Is Pretty Brilliant'.match(/ ./)STDOUT:IAs you can see in the output, the method just returns the first match rather than all the matches. In order to find further matches, we can pass a second argument to the match method. When the second parameter is present, it specifies the position in the string to begin the search. Let's find out the second character preceded by space:'RubyMonk Is Pretty Brilliant'.match(/ ./,9)OUTPUT WINDOWSTDOUT:PAll the complex use cases of this method though involves more advanced Regular Expressions, 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!aaaaaaaaaaaaaaaaaaaaqwww


	
				
		
原创粉丝点击