Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • split ,find_index , map and capitalize methods in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 615
    Comment on it

    Strings in Ruby have an instance method namely split that splits the given String and returns an array of substrings based on the separator given as an argument to it.

    have a look at these examples:

    gauravjhadiyal@gauravjhadiyal:~$ irb
    2.1.5 :001 > "this-is-a-ruby-string".split("-")
     => ["this", "is", "a", "ruby", "string"] 
    2.1.5 :002 > "another/example".split("/")
     => ["another", "example"] 
    2.1.5 :003 > "second example for rubyists".split(" ")
     => ["second", "example", "for", "rubyists"] 
    

    find_index instance method of Array returns the first index of the given parameter depending on the presence of it within the array.

    2.1.5 :004 > ["1","45","23","12"].find_index("12")
     => 3 
    2.1.5 :005 > ["1","45","23","12"].find_index("11")
     => nil 

    map method is also an instance method available with Array .It simply iterates through an array ,passes each element to a block and creates a brand-new-array accumulating all the values returned from the block.

    2.1.5 :007 > squares = [7,2,19,23].map { |number| number ** 2}
     => [49, 4, 361, 529] 
    2.1.5 :008 > p squares
    [49, 4, 361, 529]
     => [49, 4, 361, 529] 

    The internal implementation of map method looks akin to this:

    class Array
      def map
         output = []
         self.each do |item|
            output << yield(item)
         end
         output
      end
    end

    and lastly,capitalize method works like this:

    2.1.5 :011 > "sample_string".capitalize
     => "Sample_string" 
    2.1.5 :012 > "string".capitalize
     => "String" 
    

    Thanks a lot for Reading.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: