Skip to content

Instantly share code, notes, and snippets.

@prashanth-sams
Last active May 6, 2019 01:51
Show Gist options
  • Save prashanth-sams/3dd31d4d95ca70c81ffb6d1eb967da1d to your computer and use it in GitHub Desktop.
Save prashanth-sams/3dd31d4d95ca70c81ffb6d1eb967da1d to your computer and use it in GitHub Desktop.
Ruby Basics

iteration

sams = ["s", "a", "m", "s"]
sams.map! do |val|
  val.upcase
end
puts sams

exclamation in Ruby

sams = "sams"
k = sams.upcase!
puts k
puts sams

upcase and move array of string to another array

sams = ["s", "a", "m", "s"]
k = Array.new
sams.map! do |val|
  k.push(val.upcase)
end
puts k

or

sams = ["s", "a", "m", "s"]
sams.map {|i| i.upcase}

or

sams = ["s", "a", "m", "s"]
sams.map!(&:upcase)

increment value using array size

k = Array.new(20)
i = 0
k.map do |val|
  puts i
  i = i + 1
end

(or)

k = Array.new(20)
k.each_with_index do |val, i|
  puts i
end

how to modify the array of values and update in another array

arr = [1, 3]
k = arr.map.with_index { |val, i| [val + i] }
puts k

generate random values in an array

x = (1..10).to_a.shuffle

methods

a = 4
a.between?(5,6)

=> true

a = "my rank is 2"
a.include?("2")

=> true

a = ["1", "2", "6"]
a.include?("2")

=> true

a = ["1", "5"]
b = ["1", "5"]
a <=> b

=> 0

a = ["1", "5"]
b = ["1", "2"]
a <=> b
or
4 <=> 1

=> 1

a = ["1", "2"]
b = ["1", "5"]
a <=> b
or
1 <=> 4

=> -1

a = ["1", "5"]
b = 0
a <=> b

=> nil

a = [1, 2, 3]
b = [1, 2, 3]
a.eql?b
a.equal?b
4.eql?4
4.equal?4

=> true

odd numbers

odd = Proc.new {|i| i % 2 == 1 }
[1,2,3,4,5,7].select(&odd)

=> [1, 3, 5, 7]

even numbers

even = Proc.new {|i| i % 2 == 0 }
[1,2,3,4,5,7].select(&even)

or

even = lambda {|i| i % 2 == 0 }
[1,2,3,4,5,7].select(&even)

=> [2, 4]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment