Write a Ruby program to compute the sum of elements in a given array.

  1. Ruby Code: nums = [12, 34, 23, 56] print “Original array:\n” print nums print “\nSum of the values of the above array:\n” print nums.inject(0){|sum,x| sum + x }
  2. Flowchart:
  3. Ruby Code Editor:
  4. Contribute your code and comments through Disqus.

How do you sum in Ruby?

Ruby | Enumerable sum() function The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable. If a block is given, the block is applied to the enumerable, then the sum is computed. If the enumerable is empty, it returns init. Parameters: The function accepts a block.

What does .index do in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found.

What is inject in Ruby?

The #inject method acts the same as the #reduce method, and they are considered aliases. These enumerator methods can take a range or array of numbers, and can optionally receive a block. When called, the inject method will pass each element and accumulate each sequentially.

How do you add an array?

Using ArrayList Hence this process involves the following steps. Convert Array into ArrayList using asList() method. Add elements into the array list using the add() method. Convert the ArrayList again to the array using the toArray() method.

How do you calculate an array?

Starts here3:28How to Create Array Formulas in Excel – YouTubeYouTube

What is Each_with_index in Ruby?

The each_with_index() of enumerable is an inbuilt method in Ruby hashes the items in the enumerable according to the given block. Return Value: It returns the enumerator, if no block is given, else it hashes the items.

How does Ruby injection work?