Hi Readers,
Today we are going to learn how to write case statements in Ruby. Know about ruby blocks and some string operations with examples.
Today we are going to learn how to write case statements in Ruby. Know about ruby blocks and some string operations with examples.
Case:
x = 11
case x
when 0
when 1, 2..5
puts "Second branch"
when 6..10
puts "Third branch"
when *[11, 12]
puts "Fourth branch"
when String: puts "Fifth branch"
when /\d+\.\d+/
puts "Sixth branch"
when x.to_s.downcase == "peter"
puts "Seventh branch"
else
puts "Eight branch"
end
case x
when 0
when 1, 2..5
puts "Second branch"
when 6..10
puts "Third branch"
when *[11, 12]
puts "Fourth branch"
when String: puts "Fifth branch"
when /\d+\.\d+/
puts "Sixth branch"
when x.to_s.downcase == "peter"
puts "Seventh branch"
else
puts "Eight branch"
end
Blocks - Usage examples:
# Iteration
[1, 2, 3].each { |item| puts item }
# Resource Management
File.open("file.txt", "w") do |file|
file.puts "foobar"
end
# Callbacks
widget.on_button_press do
puts "Got button press"
end
# Convention: one-line blocks use {...} and multiline
# blocks use do...end
[1, 2, 3].each { |item| puts item }
# Resource Management
File.open("file.txt", "w") do |file|
file.puts "foobar"
end
# Callbacks
widget.on_button_press do
puts "Got button press"
end
# Convention: one-line blocks use {...} and multiline
# blocks use do...end
Common String Operations:
" ".empty? == true
IO.read(__FILE__).each_with_index { |line, i| puts "#{i}: #{line}" }
"abc".scan(/./).each { |char| char.upcase }
"we split words".split.join(", ")
" strip space ".strip
sprintf("value of %s is %.2f", "PI", 3.1416)
"I Go Ruby"[2, 2] == "I Go Ruby"[2..3] # => "Go"
IO.read(__FILE__).each_with_index { |line, i| puts "#{i}: #{line}" }
"abc".scan(/./).each { |char| char.upcase }
"we split words".split.join(", ")
" strip space ".strip
sprintf("value of %s is %.2f", "PI", 3.1416)
"I Go Ruby"[2, 2] == "I Go Ruby"[2..3] # => "Go"
Hope you will understand this concepts. Next we will meet with different concept.
Please practice these to get hands on experience.
Share if you like else comment.
No comments:
Post a Comment