Re: Need to advice: i want to reduce code lines
Brandon Weaver <[email protected]>
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <CAH7vphQHiBnkKk6dUR6Ugz5ELfz1PT1BPiZTvjezMNNJQWO5vQ@mail.gmail.com> |
The main thing you can do is not use regex to get each consecutive two
digits of a string. Just use indexes on strings.
An extract_date function might look something like this once cleaned up:
def extract_date(date_string)
year = "20#{date_string[0..1]}".to_i
month = date_string[2..3].to_i
day = date_string[4..5].to_i
DateTime.new(day, month, year, 0, 0, 0, 0.375)
end
I would leave the offsetting (21 and 35) outside of this function, as it's
a separate concern. I would also give names to those values, which I'd
guess are 3 and 5 week intervals respectively.
Now on to the unix code you have above, there are ways to get the same data
in Ruby:
def load_data(source_url: FULL_URL)
Net::HTTP
.get(URI(source_url))
# Gets the lines of a String
.lines
# Lines that start with 4 digits and have NA in there, avoids blanks
.grep(/^\d{4}.*NA/)
# Use the | delimiter to get the 1st and 3rd value
.map { |line| line.split(/ | /).values_at(0, 2) }
# Since you want in groups of the 1st and 3rd this would line them
# back up
.transpose
end
There are some which would (*fairly) say that transposing and extracting
the data isn't the concern of that function. That'd be a refactoring left
as an exercise to the reader, as I'm not aiming for perfect code in this,
just demonstrating ideas.
On Mon, Jan 21, 2019 at 3:06 AM Brandon Weaver <[email protected]>
wrote:
> Could you describe what the data is and what you want to do with it?
>
> On Mon, Jan 21, 2019 at 2:48 AM Byung-Hee HWANG (황병희, 黃炳熙) <
> [email protected]> wrote:
>
>> Hi, i wrote some ruby codes that used hanwoo breeding. That is so long
>> line. Is
>> that possible to reduce lines? And i'm new to ruby. Thanks in advance!!!
>>
>> Here are the codes:
>> https://gitlab.com/soyeomul/hanwoo/raw/master/z001.rb
>>
>> --
>> ^고맙습니다 _地平天成_ 감사합니다_^))//
>>
>>
>> Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
>> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
>>
>
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>