[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement

(ruby 2.5.3)

Conclusion

When you want to rotate a JavaScript iterative statement while making changes to array elements

for (var i = 0; i < A.length; i++){
 // Omitted: Change the value of A [i] under certain conditions
}

If you want to reproduce in Ruby in the same atmosphere

 A.each_index do |i|
 ## Omitted: Change the value of A [i] under certain conditions
end

I will write.

background

I was rewriting my private code written in JavaScript into Ruby. The following JavaScript function is a part of it, and when English parts are passed in an array, the beginning of the word corresponding to the beginning of the sentence is changed to uppercase by the symbol at the end and combined and output.

function Upcasing(result_lines) {
  result_lines[0] = result_lines[0].replace(/^[a-z]/, result_lines[0].charAt(0).toUpperCase() );
  var break_flg = false;
  const break_sign = { ".":true, "!":true, "?":true, ",":false };
  for (var i = 0; i < result_lines.length; i++) {
    if (break_flg === true) {
      result_lines[i] = result_lines[i].replace(/^[a-z]/, result_lines[i].charAt(0).toUpperCase() );
    }

    if ( break_sign[result_lines[i].slice(-1)] === true) {
      break_flg = true;
    } else {
      break_flg = false;
    }
  }
  return result_lines.join(" ");
}

console.log(Upcasing(["oh,", "yeah!", "hello!"]));

 // Execution result
// Oh, yeah! Hello! 
 // <= What was "hello!" Is capitalized at the beginning of the next word due to the previous "!"

The following is what I rewrote (I thought) to the Ruby method as it is.

def Upcasing(result_lines)
  result_lines[0] = result_lines[0].capitalize
  break_flg = false
  break_sign = { "."=>true, "!"=>true, "?"=>true, ","=>false }

  for r in result_lines
    if break_flg == true
      r = r.capitalize
    end

    if break_sign[r.slice(-1)] == true
      break_flg = true
    else
      break_flg = false
    end
  end
  joined_line = result_lines.join(" ")
  return joined_line
end

print Upcasing(["oh,", "yeah!", "hello!"])

## Execution result
## Oh, yeah! hello! <= "H" in "hello!" Is not capitalized

Since the for expression does not create a scope like the ```each method , the rof the for r in result_linescan be used outside the block, but in the first place it is with the original array element. Is a newly defined variable, so if you want to make changes to the array elements, you need to manipulate results_lines [i] even inside the block. (This variable r`` is not a block parameter.)

Usually, when writing Ruby code, there are not many scenes where values are assigned in repeating blocks, so the concept of temporary boxes such as block parameters and recognition of the generated scope are lacking. It was.

-Control Structure> for | Ruby 2.7.0 Reference Manual

-Method call with block | Ruby 2.7.0 Reference Manual

-module Enumerable | Ruby 2.7.0 Reference Manual

(* The one used in this memorandum is ruby 2.5.3.)

In the form of for variable name in array name like the above code, the index for specifying the array element in the block is not defined in the variable, so use the `ʻeach_index method`` and use the following Changed to. (The code below was refactored in an article posted at a later date.)

def Upcasing(result_lines)
  result_lines[0] = result_lines[0].capitalize
  break_flg = false
  break_sign = { "."=>true, "!"=>true, "?"=>true, ","=>false }

   result_lines.each_index do |i|
    if break_flg == true
      result_lines[i] = result_lines[i].capitalize
    end

    if break_sign[result_lines[i].slice(-1)] == true
      break_flg = true
    else
      break_flg = false
    end
  end
  joined_line = result_lines.join(" ")
  return joined_line
end

print Upcasing(["oh,", "yeah!", "hello!"])

## Execution result
 Oh, yeah! Hello!

(For this time, since there is no need to use the variable defined in the repeating block outside, there is no effect on the whole depending on whether the scope is generated by for expression or ```each method ``. .)

Impressions

I think that omitting the variable name and reducing the amount of sentences is a big advantage of using block parameters, but if the array element is changed in the iterative process, it may not be used much. I thought about passing the value and index to the block parameter with the ʻeach_with_index method as shown in the draft below and using it only in the part that refers to the current element, but I feel that mistakes may increase. And stopped. The variable name is| r |Not| current_element |It may still be easy to understand.

result_lines.each_with_index do |current_element, i|
 if break_flg == true
   result_lines[i] = current_element.capitalize
 end

 if break_sign[current_element.slice(-1)] == true
   break_flg = true
 else
   break_flg = false
 end
end

-each_with_index (* args)-> Enumerator | Ruby 2.7.0 Reference Manual

Recommended Posts

[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement
How to retrieve the hash value in an array in Ruby
How to output the value when there is an array in the array
How to change a string in an array to a number in Ruby
How to specify an array in the return value / argument of the method in the CORBA IDL file
[Java] How to search for a value in an array (or list) with the contains method
How to change the value of a variable at a breakpoint in intelliJ
[Swift] How to get the number of elements in an array (super basic)
[Java] How to convert one element of a String type array to an Int type
How to start a subscript from an arbitrary number in Ruby iterative processing
How to find the total value, average value, etc. of a two-dimensional array (multidimensional array)-java
Offline real-time how to write Implementation example of the problem in E05 (ruby, C11)
How to request by passing an array to the query with HTTP Client of Ruby
[ruby] How to assign a value to a hash by referring to the value and key of another hash
Determine that the value is a multiple of 〇 in Ruby
[Ruby] How to retrieve the contents of a double hash
How to add the same Indexes in a nested array
[Ruby] How to batch convert strings in an array to numbers
[Ruby] How to extract a specific value from an array under multiple conditions [select / each]
[Ruby] How to count even or odd numbers in an array
[Swift5] How to get an array and the complement of arrays
[Ruby] I want to put an array in a variable. I want to convert to an array
How to write ruby if in one line Summary by beginner
Cast an array of Strings to a List of Integers in Java
I want to change the value of Attribute in Selenium of Ruby
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
How to write the view when Vue is introduced in Rails?
How to write when you want to handle "array of C language strings" like argv [] in Ruby-FFI
I tried to make a parent class of a value object in Ruby
[Java] How to turn a two-dimensional array with an extended for statement
How to convert an array of Strings to an array of objects with the Stream API
Get the type of an array element to determine if it is an array
How to set an image in the drawable Left / Right of a button using an icon font (Iconics)
How to find the total number of pages when paging in Java
How to constrain the action of the transition destination when not logged in
How to get the absolute path of a directory running in Java
Android development, how to check null in the value of JSON object
[Ruby] How to prevent errors when nil is included in the operation
How to reference a column when overriding the column name method in ActiveRecord
How to insert processing with any number of elements in iterative processing in Ruby
When reassigning to an argument in a Ruby method and then calling `super` → The reassigned one is used
Use hashes well in Ruby to calculate the total amount of an order
graphql-ruby: How to get the name of query or mutation in controller Note
[Ruby] Learn how to use odd? Even? And count the even and odd numbers in the array!
If the parameter is an array, how to include it in Stopara's params.permit
How to get the ID of a user authenticated with Firebase in Swift
How to check if an instance variable is defined in a Ruby class
[Ruby] Meaning of &. How to avoid the error when the receiver (object) is nil
[Swift] How to change the order of Bar Items in Tab Bar Controller [Beginner]
How to make a unique combination of data in the rails intermediate table
I made a sample of how to write delegate in SwiftUI 2.0 using MapKit
How to find the cause of the Ruby error
[Rails] How to write when making a subquery
How to write an if statement to improve readability-java
How to build the simplest blockchain in Ruby
I want to get the value in Ruby
[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.
[Ruby On Rails / HTML] How to display the cursor (caret) at an appropriate place when displaying a web page
[Java] When putting a character string in the case of a switch statement, it is necessary to make it a constant expression
Speed comparison when the value side of Hash wants to retrieve all with array