[Ruby] Thinking about logic Ruby

5 minute read

Embody what you want to do with code

Briefly, it’s difficult to play. I want to increase the number of expressions I can use, but rather, I am bound by the constraints of what I have learned, and I can only use this with this kind of feeling, then there are many people who are worried about how I can do what I want to do in the code…I am still immature. , I have many experiences like this. In this article, I’ll summarize what I learned from the problems in my code and organize my thoughts for each case.

First, the expression is redundant

arr_year.rb


     date = []

     registerd_list.each do |data|
       date.push data.createdAt
     end

     cnt = 0
     date.each do |data|
       if date.year == data.year
         cnt += 1
       end
     end
     cnt

This is a substitute for looping through the data of an object that inherits a certain Enumerable class, plunging the created date in the data into an array, and counting only the ones in which the year corresponds to the present .. This is good,

arr_year_kai.rb


registerd_list.select {|data| data.created_at.year == date.year}.size

It can be expressed with just one line. We are using the select and size methods here. ruby has a large number of methods that can be used for each class. There are quite a few array manipulation methods.

class Array Ruby Reference

select method

Returns an array containing all the elements for which the value of the block evaluated for each element was true. Returns an empty array if no elements are true.

It’s convenient. It is a method that combines the ability of each and if to loop and also put the condition in it.

size method

Returns the length of the array. Returns 0 if the array is empty.

It is the same expression as length or count.

I can make a method chain with {}.size. It seems that you can also do end.size. Now you can smash a few lines of code into a single line for both rabbits and horns. No, I’m afraid.

Second, there are many literal notations

What is the number used in a single shot, also called a magic number? It is necessary to devise such a code as to be read back or to have someone read it, because it is difficult to understand what this number represents, or it is necessary to add meaning. There is.

Example without magic number

magick_num.rb


 def self.get_year

     year = Time.new.year + 1
     years = []
     while year >2017 do
       year = year-1
       years.push year
     end
     years
   end

This is a process that I made to make select forms from 2017 to this year, I think that it will be +1 or -1, but if you do not do this, it will come out from 2017 to this year It is. I’m starting this year with the Time object.

improved_year.rb


 def self.get_years
     (2017..Time.new.year).to_a.reverse
   end

Yes, it’s just one line. I’m using a range object that has a method chain, to_a and reverse.

to_a method

returns self. However, when called on an instance of a subclass of Array, it returns an Array converted to itself.

reberse method

reverse creates and returns a new array with its elements in reverse order. reverse! rearranges itself destructively. reverse! returns self.

So, by re-arranging it and reversing its elements, we have been able to neatly arrange it from the latest year, and the magic number has also disappeared.

Day of the week compared by number

w.rb


      if full_week_of_one_month.wday == 0
        calculation_result_of_amounts.push cnt
        cnt = 0
      else
        calculation_result_of_amounts.push ""
      end

The above is a part of the code when creating the array of calculation results, but since I wanted to push only on a specific day of the week, I use the day of the week in the conditional expression. In ruby, the day of the week is expressed as 1 for Monday and 0 for Sunday, so I wanted to determine Sunday, so I used 0, but it seems to be 6 of these.

w_kai.rb


      WEEK_SUNDAY = 0

      if full_week_of_one_month.wday == WEEK_SUNDAY
        calculation_result_of_amounts.push cnt
        cnt = 0
      else
        calculation_result_of_amounts.push ""
      end

At times like this, the numbers are given meaning to solve them. It can be reused at another place if it is made constant. In this case, it is easy to understand what they mean and compare.

Third, understand initialization

Importance of initialization and substitution. It’s only natural to breathe, but it’s easy to forget. The code below loops endlessly. That’s right, because we haven’t re-entered year in a variable, so it’s still bigger than 2017.

infiniting_roop.rb


def self.get_year
     year = Time.new.year + 1

     while year >2017 do
       year-1
       p year
     end
   end

It will look like the one below. If you put it in the variable again, the year minus 1 will be used as the year in the conditional expression for the next loop, so it will only need to be subtracted until the condition is reached using the properly drawn years.

modified_roop.rb


def self.get_year
     year = Time.new.year + 1

     while year >2017 do
       year = year-1
       p year
     end
   end

Use initialization

This is a part of the code that is processing to move to the next week’s count after the data for one week has been aggregated. It is a process that loops the outline for one month’s date, creates a loop for summing the dates for one week in it, pushes the data to the array when one week is reached, and initializes the count at this point .. Put it in a loop as a conditional expression and reset the cnt’ed number to 0.

calk_date.rb


    cnt = 0
    amounts_of_calculation_result = []
    (beginning_week..last_week_of_next_month).each do |date|
      users_dates.each do |user_date|
        if date.year == user_date.year && date.day == user_date.day
            cnt += 1
        end
      end

      if date.wday == WEEK_SUNDAY
        amounts_of_calculation_result.push cnt
        cnt = 0
      end
    end
    amounts_of_calculation_result

No, no, no, no

So, when thinking about logic, there are abundant methods, avoid literal expressions or make sense, and use initialization to express what you want to do. It’s about combining the expressions you’ve got to form a logic. I want to keep an eye on the expressions that have become usable, and to output them each time.