read_a_configuration_file.sf 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Read_a_configuration_file
  4. #
  5. var fullname = (var favouritefruit = "");
  6. var needspeeling = (var seedsremoved = false);
  7. var otherfamily = [];
  8. DATA.each { |line|
  9. var(key, value) = line.strip.split(/\h+/, 2)...;
  10. given(key) {
  11. when (nil) { }
  12. when (/^([#;]|\h*$)/) { }
  13. when ("FULLNAME") { fullname = value }
  14. when ("FAVOURITEFRUIT") { favouritefruit = value }
  15. when ("NEEDSPEELING") { needspeeling = true }
  16. when ("SEEDSREMOVED") { seedsremoved = true }
  17. when ("OTHERFAMILY") { otherfamily = value.split(',')»strip»() }
  18. default { say "#{key}: unknown key" }
  19. }
  20. }
  21. say "fullname = #{fullname}";
  22. say "favouritefruit = #{favouritefruit}";
  23. say "needspeeling = #{needspeeling}";
  24. say "seedsremoved = #{seedsremoved}";
  25. otherfamily.each_kv {|i, name|
  26. say "otherfamily(#{i+1}) = #{name}";
  27. };
  28. assert_eq(fullname, 'Foo Barber');
  29. assert_eq(favouritefruit, 'banana');
  30. assert_eq(needspeeling, true);
  31. assert_eq(seedsremoved, false);
  32. assert_eq(otherfamily[0], 'Rhu Barber');
  33. assert_eq(otherfamily[1], 'Harry Barber');
  34. __DATA__
  35. # This is a configuration file in standard configuration file format
  36. #
  37. # Lines beginning with a hash or a semicolon are ignored by the application
  38. # program. Blank lines are also ignored by the application program.
  39. # This is the fullname parameter
  40. FULLNAME Foo Barber
  41. # This is a favourite fruit
  42. FAVOURITEFRUIT banana
  43. # This is a boolean that should be set
  44. NEEDSPEELING
  45. # This boolean is commented out
  46. ; SEEDSREMOVED
  47. # Configuration option names are not case sensitive, but configuration parameter
  48. # data is case sensitive and may be preserved by the application program.
  49. # An optional equals sign can be used to separate configuration parameter data
  50. # from the option name. This is dropped by the parser.
  51. # A configuration option may take multiple parameters separated by commas.
  52. # Leading and trailing whitespace around parameter names and parameter data fields
  53. # are ignored by the application program.
  54. OTHERFAMILY Rhu Barber, Harry Barber