Comparison of for instructions to fetch arrays sequentially

I can't go anywhere during GW, so I'm studying Java at home. The ruby each statement is excellent, and I'm happy that it can be used anywhere, so I use it a lot. How do you write a for statement in ruby when you are using ruby? I feel like. For example, when outputting the contents of an array, you can write it like this.

 fruits = ["apple", "orange", "banana"]
 fruits.each do |v|
  print "#{v}\n"
end

If this is written in C # with a for statement, it looks like this.

 var fruits = new string [] {"apples", "mandarins", "bananas"};
for (int i = 0; i < fruits.Length; i++)
{
	Console.WriteLine(fruits[i]);
}

This is an orthodox method of fetching elements by turning the index of an array with the counter of the for statement. And there is a foreach statement in a notation like Ruby's each, and you can write like this.

 var fruits = new string [] {"apples", "mandarins", "bananas"};
foreach (var v in fruits)
{
	Console.WriteLine(v);
}

The foreach statement can retrieve elements of a class that implements the ʻIEnumerable or ʻIEnumerable <T> interface. It seems that the array can be used because it implements ʻIEnumerable. List etc. can also be used because they implement ʻIEnumerable <T>.

In the case of Java, there seems to be an extended for statement, and it seems to write like this.

 var fruits = new String [] {"apples", "mandarins", "bananas"};
for (var v : fruits)
{
	System.out.println(v);
}

Well, it's hard to understand. You write with the same for instead of foreach.

For C #, you can do the same a little smarter by using a lambda expression with a List.

 var fruits = new List <string> {"apples", "mandarins", "bananas"};
fruits.ForEach(v => Console.WriteLine(v));

By the way, although it is different from the main point of this time, Join is enough if you just want to output the contents of the array with line breaks.

 var fruits = new List <string> {"apples", "mandarins", "bananas"};
Console.WriteLine(string.Join("\n", fruits.ToArray()));

Personally, I like the ruby notation, which is the origin.

 fruits = ["apple", "orange", "banana"]
print fruits.join("\n")

Recommended Posts

Comparison of for instructions to fetch arrays sequentially
Comparison of compression libraries for JavaVM
[Introduction to Java] Basics of java arithmetic (for beginners)
How to specify index of JavaScript for statement
Java Welcome to the Swamp of 2D Arrays
Corresponds to 17 arrays
Initialization of for Try to make Java problem TypeScript 5-4
Procedure to use S3 of LocalStack for Active Storage
Introduction to Java for beginners Basic knowledge of Java language ①
List of frequently used Java instructions (for beginners and beginners)
How to execute WebCamCapture sample of NyARToolkit for Java