Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Join and Inject methods for arrays (Ruby)

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3
    • 0
    • 810
    Comment on it

    Join and Inject methods for arrays in ruby

    Join method is used to combine all array elements into one string.

    With the help of join method we can combine a lot of strings present in an array into one single string.

    Join method can also be used to insert something between strings
    Example 1:

    In the below screenshot we can clearly see what join method did. It joined both the strings.


    We can also insert something between two strings with the help of join method like this.

    Now, Use the Array#join method (the argument to join is what to insert between the strings - in this case a space) :@arr.join(", ")

    Example 2:

    Whereas, Inject method combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.

    If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.

    If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

    Examples:

    Join and Inject methods for arrays (Ruby)

 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: