Tabela de Conteúdos
:: Topo :: doCoding :: Linguagens de Programação :: Ruby :: FORPC101 ::
Week-02
Aprendizagem
- A forma de capturar input interactivamente é trapalhona:
Capture Input
STDOUT.flush varName = gets.chomp
- Variáveis e Scope - muito bom, onde realmente a notação faz a diferença: @@, @, $.
- one and only one self - o objecto corrente ou por omissão acessível ao programa.
- Bang Methods - métodos com terminação !, que alertam sobre o facto de efectuarem alterações ao próprio objecto passado como argumento.
- “string” * n - imprime a string n vezes. Muito bom.
- String.slice e String.join - idênticos aos em Perl. Muito bom.
- É possível ter aliases de métodos. O que pode tornar a passagem de uma outra linguagem para Ruby ainda mais “transparente”.
Exercícios
Exercício 1
exercise-01.rb
=begin Write a method called convert that takes one argument which is a fixed temperature value in Fahrenheit. The method returns the temperature value in Centigrade. =end =begin http://en.wikipedia.org/wiki/Fahrenheit TC = (TF - 32) * 5/9 TF = (TC * 9/5) + 32 =end # By using a default value of -40.0 the variable is "forced" into a Float. # This has the side-effect (good) of returning a float as well. def convert(temperature_in_fahrenheit = -40.0) temperature_in_centigrade = (temperature_in_fahrenheit - 32) * 5 / 9 end puts "Default Conversion is -40ºF to " + convert.to_s + "ºC" test_temperature_in_fahrenheit = -459.67 puts test_temperature_in_fahrenheit.to_s + "ºF is " + convert(test_temperature_in_fahrenheit).to_s + "ºC" test_temperature_in_fahrenheit = 32 puts test_temperature_in_fahrenheit.to_s + "ºF is " + convert(test_temperature_in_fahrenheit).to_s + "ºC" test_temperature_in_fahrenheit = 212 puts test_temperature_in_fahrenheit.to_s + "ºF is " + convert(test_temperature_in_fahrenheit).to_s + "ºC"
Exercício 2
exercise-02.rb
=begin The following program: > arg1="Satish", arg2="Sunil", arg3="Marcos" > puts "#{arg1}, #{arg2}, #{arg3}." when executed, outputs: > SatishSunilMarcos, Sunil, Marcos. Why? =end arg1="Satish", arg2="Sunil", arg3="Marcos" puts "#{arg1}, #{arg2}, #{arg3}." # Because arg1 is seen by Ruby as an Array with 3 elements. arg1 = [ "Satish", arg2 = "Sunil", arg3 = "Marcos" ] puts "#{arg1}, #{arg2}, #{arg3}." # It implictly surrounds the statement with commas with square-brackets. # These following forms don't trigger arg1 to be an array: arg1 = "Satish"; arg2 = "Sunil"; arg3 = "Marcos" puts "#{arg1}, #{arg2}, #{arg3}." arg1 = "Satish" arg2 = "Sunil" arg3 = "Marcos" puts "#{arg1}, #{arg2}, #{arg3}."
Exercício 3
exercise-03.rb
=begin Write a Ruby program (p006ftoc.rb) that asks for a numeric value of the temperature in degrees Fahrenheit. Finally, the program displays the equivalent value in degrees Centigrade. To format the output to say 2 decimal places, we can use the Kernel's format method. For example, if x = 45.5678 then format("%.2f", x) will return a string 45.57. Another way is to use the round function as follows: puts (x*100).round/100.0 =end =begin http://en.wikipedia.org/wiki/Fahrenheit TC = (TF - 32) * 5/9 TF = (TC * 9/5) + 32 =end # By using a default value of -40.0 the variable is "forced" into a Float. # This has the side-effect (good) of returning a float as well. def f2c(temperature_in_fahrenheit = -40.0) temperature_in_centigrade = (temperature_in_fahrenheit - 32) * 5 / 9 end def c2f(temperature_in_centigrade = -40.0) temperature_in_fahrenheit = (temperature_in_centigrade - 32) * 5 / 9 end puts "Conversion Options:\n\tc - Centigrade to Fahrenheit\n\tf - Fahrenheit to Centigrade " print "Select Conversion Options: " STDOUT.flush conversion_option = gets.chomp if conversion_option == 'c' or conversion_option == 'f' then print "Input Temperature Value to Convert " if conversion_option == 'c' then print "from Centigrades to Fahrenheit: " end if conversion_option == 'f' then print "from Fahrenheit to Centigrades: " end STDOUT.flush temperature = gets.chomp temperature = temperature.to_f if conversion_option == 'c' then puts format("%.2f", temperature.to_s) + "ºC is " + format("%.2f", c2f(temperature).to_s) + "ºF." end if conversion_option == 'f' then puts format("%.2f", temperature.to_s) + "ºF is " + format("%.2f", f2c(temperature).to_s) + "ºC." end else puts "Unknown Conversion Option!" end
Exercício 4
exercise-04.rb
=begin Write a Ruby program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". This exercise is courtesy Chris Porter. =end # times starts at 0 #100.times do |number| # number = number + 1 # puts number.to_s #end # step starts at arg1, loops until arg2, incremented by optional arg3 = 1 1.step(100) do |number| is_multiple = false if number % 3 == 0 then print "Fizz" is_multiple = true end if number % 5 == 0 then print "Buzz" is_multiple = true end if !is_multiple then puts number.to_s else print "\n" end end
Questionário
Referências
Considerações
Pontos Altos
Esta secção regista o que considero serem os pontos altos da linguagem Ruby quando comparada com outras linguagens que conheço.
Pontos Baixos
Esta secção regista o que considero serem os pontos baixos da linguagem Ruby quando comparada com outras linguagens que conheço.
- A captura de input interactivamente. Esperava algo mais simples e mais poderoso. Como se capturam teclas especiais: Esc, Alt, Ctrl, etc.?
- Os cálculos com Floats podem diferir em deltas inferiores a 1.0e-014.