Skip to main content

Ruby Formatting, ljust rjust, regex, .count

- Didn't realise that nil.to_i = 0
https://stackoverflow.com/questions/11029256/difference-between-nil-blank-and-empty

- Interesting that .count and .size doesn't just count number of elements in array.
If I did (1..5).count or .size # => 5
If I did .length, it would have an error.

.count { | i | not i.to_s.include? '5' } can be used as a block.

- .reject
It's cool that reject blocks can be used in this manner:
1) .reject { |e| e.to_s.include?('5') }
2) .reject { |n| n.to_s =~ /5/ }
Both achieve the same thing.

- Ruby formatting.
This is very new to me.
("%-5s" % "teg") => "teg  "
It's like saying the format is 5 characters in a sring.
https://idiosyncratic-ruby.com/49-what-the-format.html

- .ljust
expands the string or if there is an integer, fills the strings to the number of characters.
"hello".ljust(4)            #=> "hello"
"hello".ljust(20)           #=> "hello               "
"hello".ljust(20, '1234')   #=> "hello123412341234123"

The reverse of it is rjust
"hello".rjust(4)            #=> "hello"
"hello".rjust(20)           #=> "               hello"
"hello".rjust(20, '1234')   #=> "123412341234123hello"

- Good ideal to use the regex at some problems.
"123abc" !~ /\D/ # => false
"123" !~ /\D/ # => true

- Love this link for arrays https://docs.ruby-lang.org/en/2.0.0/Array.html

- This method is cool to reformat dates
require 'time'
  time = Time.parse("01-Jan-2000")  => 2000-01-01 00:00:00 +0800
  @formattedTime = time.strftime("%d/%m/%y") => "01/01/00"

Comments