J
John Crichton
I am fairly new to Ruby and programming and had a couple questions about
if/else and case statements. I was wondering if there were benefits to
using case statements instead of if/elsif/else type statements. Are
case statements faster?
If I am reading in a file line by line and doing something similar to
lines = File.open("file.csv")
FasterCSV.parse(lines) do |row|
if ( lines =~ /^blah/)
puts "blahblahblah"
some_method
end
if ( lines =~ /^name/ && row[1] =="123")
puts "ping pong abc"
another_method
end
if ( lines =~ /^address/ && row[3] =="XYZ")
puts "abcdefghijklmnopqrstuvwxyz"
method3
end
end
Does writing it with a case statement like so benefit me?
lines = File.open("file.csv")
FasterCSV.parse(lines) do |row|
case
when ( lines =~ /^blah/)
puts "blahblahblah"
some_method
when ( lines =~ /^name/ && row[1] =="123")
puts "ping pong abc"
another_method
when ( lines =~ /^address/ && row[1] =="XYZ")
puts "abcdefghijklmnopqrstuvwxyz"
method3
end
end
While writing this I couldn't figure out how to write my case to be "if
lines begins with"
case "lines =~"
when /^blah/
puts "blahblahblah"
some_method
Lastly is there a "better" way to write an if statement that is
conditional on a bunch of things like
if row[0] == john && row[7] == abc123 && row[8] != nil &&
somehashtable.has_key?(row2)
Thanks
if/else and case statements. I was wondering if there were benefits to
using case statements instead of if/elsif/else type statements. Are
case statements faster?
If I am reading in a file line by line and doing something similar to
lines = File.open("file.csv")
FasterCSV.parse(lines) do |row|
if ( lines =~ /^blah/)
puts "blahblahblah"
some_method
end
if ( lines =~ /^name/ && row[1] =="123")
puts "ping pong abc"
another_method
end
if ( lines =~ /^address/ && row[3] =="XYZ")
puts "abcdefghijklmnopqrstuvwxyz"
method3
end
end
Does writing it with a case statement like so benefit me?
lines = File.open("file.csv")
FasterCSV.parse(lines) do |row|
case
when ( lines =~ /^blah/)
puts "blahblahblah"
some_method
when ( lines =~ /^name/ && row[1] =="123")
puts "ping pong abc"
another_method
when ( lines =~ /^address/ && row[1] =="XYZ")
puts "abcdefghijklmnopqrstuvwxyz"
method3
end
end
While writing this I couldn't figure out how to write my case to be "if
lines begins with"
case "lines =~"
when /^blah/
puts "blahblahblah"
some_method
Lastly is there a "better" way to write an if statement that is
conditional on a bunch of things like
if row[0] == john && row[7] == abc123 && row[8] != nil &&
somehashtable.has_key?(row2)
Thanks