Skip to main content

Ternary Operators, Hash and Regex

- Doing name_shuffler.rb kata and competitive_eating scoreboard.rb

- More on gsub

Basically, anything in [xxx] will be replaced. 
"hello".gsub(/[aeiou]/, '*')                  #=> "h*ll*"

the \1 means the group number. Has to come with a ([xxx]). Can be \any_number
"hello".gsub(/([aeiou])/, '<\1>')             #=> "h<e>ll<o>"

Using a block, sub everything 
"hello".gsub(/./) {|s| s.ord.to_s + ' '}      #=> "104 101 108 108 111 "

This is the use of a group name. It says to replace everything with the group name with similar words from the group. ?<groupname>[xxx] and \k<groupname>.
"hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}')  #=> "h{e}ll{o}"

This is to replace specifically. 
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"

- This is a very good reference for regex. 


- .sub(/(\S+) (\S+)/, '\2 \1') is very interesting because it means non white space characters and swap position. 

- Ruby Hashes Cheatsheet

- To sort within a hash alphabetically and return it as a hash
Hash.sort.to_h
or use .sort_by {|k,v| k}

More on sorting for hashes
http://www.rubyinside.com/how-to/ruby-sort-hash

- <=> comparison operator can be used.
# This can sort each hash in the array alphabetically by name.
@friends.sort{|a,b| a['name']<=>b['name']}

- Ternary Operators are quite useful. Below are examples of condition operators and or operators.
https://www.codecademy.com/en/forum_questions/512fd8017fbce8a187000a77
https://stackoverflow.com/questions/31393404/ruby-ternary-operator-if-else

x=['x']
x.empty? || "false"
# If x is empty, it is true if not it is false.
https://stackoverflow.com/questions/31393404/ruby-ternary-operator-if-else

- .freeze is very interesting.
freeze() public
Prevents further modifications to obj. A RuntimeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?.

This method returns self.

a = [ "a", "b", "c" ]
a.freeze
a << "z"
produces:

prog.rb:3:in `<<': can't modify frozen array (RuntimeError)
 from prog.rb:3

- remember that delete and delete_if are different. delete will return the object deleted. See competitive_eating scoreboard.rb comments. 

- sort_by does a nifty thing that can make it in descending order is I do sort_by {|x| -x["name"]}







- Interesting that inject can be in the form of inject(0) {|sum, item| sum + item}

Comments