ruby inject
To achieve the functionality of Ruby's inject
method in the C language, you would need to implement it manually. The inject
method is used to accumulate values of an array or collection into a single value, based on the result of a given operation. Here's an example of how you could implement a similar functionality in C:
#include <stdio.h>
int accumulate(int *array, int size) {
int result = array[0];
for (int i = 1; i < size; i++) {
result += array[i];
}
return result;
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
int sum = accumulate(numbers, size);
printf("The sum is: %d\n", sum);
return 0;
}
In this example, the accumulate
function takes an integer array and its size as parameters. It iterates over the array starting from the second element and accumulates the values by adding them to the result
variable. The initial value of result
is set to the first element of the array. Finally, the sum
variable in the main
function holds the accumulated value.
When you run this program, it will output:
The sum is: 15
This is the equivalent of using inject
in Ruby to accumulate the values of an array.