Skip to content

Instantly share code, notes, and snippets.

@mykiy
Last active April 5, 2018 12:02
Show Gist options
  • Save mykiy/3c852fa4eafaa097e4ba779c78c29011 to your computer and use it in GitHub Desktop.
Save mykiy/3c852fa4eafaa097e4ba779c78c29011 to your computer and use it in GitHub Desktop.
hash and symbol
arr = [4,1,2,7,"M","A","V"]
arr.partition { |a| a.is_a? String }.map(&:sort).flatten
p arr
=>
["A","V","M",1,2,4,7]
-------
a = [1, "A", nil, "M", "", '']
a.reject!{|a| a.nil? || a.to_s.empty? }
p a
=>
[1,"A","M"]
-----
Hash
----
.key, value pairs
.similar to arrays
create
----
my_hash = Hash.new
snd_hash = {}
trd_hash = Hash.new(0)
default value
------
trd_hash.default
=> 0
defining
----
malls = { #with_string
"forum" => "vadapalani",
"ea" => "rayapettah",
"spencer" => "rayapettah"
}
accesing
----
malls["forum"]
=>vadapalani
malls[:forum]
=>throw a nil
malls.each do |n,l|
puts "#{n}: #{l}"
end
-
with symbol
-----
movies = {
ironman: 4.5,
batman: 5,
superman: 4.8
}
movies[:batman]
=>
5
keys
----
movies.keys
=>
all keys
delete
-----
movies.delete(:ironman)
length
-----
movies.length
=>
2
check the keys
--------
movies.has_key?(:batman)
=>
true
movies.has_key?(:ironman)
=>
false
merging
---
movies.merge(malls) { |k,v1,v2| v1 }
if merge finds any same key in both movies and malls, it will change the key value with v1.
v1 = movies, v2 = malls
reject
----
movies.reject { |k,v| v.is_a? Integer }
if reject met the condition, it will rejects the whole key and value pair.
replace
----
movies.replace( {"show" => "no screens" } )
=>
replaced the movies hash with the above content
shift
---
remove at the fornt
movies.shift
=>
{}
slice
---
returns the has with only specified key and value pair
malls.slice("forum")
=>
to_a
---
malls.to_a
which converts the hash into nested array.
raising exception
-----
h = Hash.new { |k,v| raise ArgumentError.new("No hash key: #{k}") }
h[:a] = 4
h[:b] = 2
h[:c] = 1
h[:d] = 3
h [:a]
=>
4
h[:e]
=>
No hash key: c
sort
----
h.values.sort
=>
[1,2,3,4]
only output have changed not it returns a new hash
-----
h.sort_by { |k,v| v }
=>
{ :c => 1, :b => 2, :d => 2 }
------------------
symbol
--
Only one time created in programming
name = :velu
name.class
=>
symbol
name.object_id
=>
1111111 #sample
=>
name = "velu"
=>
1122211
name = :velu
name.object_id
=>
1111111
name.capitalize
=>
name.object_id
1111111
---------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment