diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..c99d2e7 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml index e69de29..4715692 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -0,0 +1,34 @@ +AllCops: + Exclude: + - "db/**/*" + - "config/**/*" + - "Guardfile" + - "Rakefile" + DisplayCopNames: true + +Layout/LineLength: + Max: 120 +Metrics/MethodLength: + Include: ["app/controllers/*"] + Max: 20 +Metrics/AbcSize: + Include: ["app/controllers/*"] + Max: 30 +Metrics/ClassLength: + Max: 150 +Metrics/BlockLength: + ExcludedMethods: ['describe'] + +Style/Documentation: + Enabled: false +Style/ClassAndModuleChildren: + Enabled: false + +Layout/AlignHash: + EnforcedColonStyle: key +Layout/ExtraSpacing: + AllowForAlignment: false +Layout/MultilineMethodCallIndentation: + Enabled: true + EnforcedStyle: indented + \ No newline at end of file diff --git a/.stickler.yml b/.stickler.yml index e69de29..c90ce2e 100644 --- a/.stickler.yml +++ b/.stickler.yml @@ -0,0 +1,11 @@ +linters: + rubocop: + display_cop_names: true +files: + ignore: + - "bin/*" + - "db/*" + - "config/*" + - "Guardfile" + - "Rakefile" + \ No newline at end of file diff --git a/Enumerable_Methods.rb b/Enumerable_Methods.rb index fee0ba6..5379ef0 100644 --- a/Enumerable_Methods.rb +++ b/Enumerable_Methods.rb @@ -1,231 +1,146 @@ # /usr/bin/ruby # frozen_string_literal: true - - -module Enumerable - - def my_each #This is my_each method - a = 0 - self.size.times do - yield(self[a]) - a += 1 - - end - - self +# rubocop:disable Metrics/PerceivedComplexity +# rubocop:disable Metrics/CyclomaticComplexity + + module Enumerable + # my_each method + UNDEFINED = Object.new + def my_each + result = self + return result.to_enum unless block_given? + + m = 0 + while m < result.length + yield(result[m]) + m += 1 end - - def my_each_with_index #my_each_with_index - a = 0 - self.size.times do - yield(self[a], a) - a += 1 - end - - self - + result + end + + # my_each_with_index method + def my_each_with_index + result = self + return result.to_enum unless block_given? + + m = 0 + while m < result.length + yield(result[m], m) + m += 1 end + result + end - def my_select #my_select method - myselect = [] - self.my_each do |b| - if yield (b) - myselect.push (b) - - end - - end - - myselect + # my_select method + def my_select + result = self + return result.to_enum unless block_given? + arr = [] + result.my_each do |k| + arr.push(k) if yield(k) end - - def my_all? #my_all method - myall = [] - output = true - self.my_each do |b| - if yield (b) - myall.push (b) - end - end - if myall.length == self.length - output = true - else - output = false - end - output + arr + end + + # my_all? method + def my_all?(param = nil) + k = true + if block_given? + my_each { |a| k = false unless yield a } end - - def my_any? #my_any? method - output = false - self.my_each do |b| - if yield (b) - output = true - break - - end - - end - output + if param.class == Regexp + my_each { |a| k = false unless a =~ param } + elsif param.class == Class + my_each { |a| k = false unless a.is_a?(param) } + elsif !param.nil? + my_each { |a| k = false unless a == param } end - - def my_none? #my_none methods - output = true - self.my_each do |b| - if yield (b) - output = false - break - end - end - output + if param.nil? + my_each { |a| k = false unless a } end - - def my_count parameter = nil #my_count method - mycount = 0 - self.my_each do |b| - if parameter != nil - if parameter == self[b] - mycount += 1 - end - else - if yield (b) - mycount += 1 - self.my_each do |element| - if parameter - if element == parameter - mycount += 1 - end - end - elsif block_given? - mycount += if yield(element) - else - mycount = self.length - end - end - mycount - end - - def my_map #my_map method - mymap = [] - self.my_each do |b| - mymap.push yield(b) - end - mymap + k + end + + # my_any? method + def my_any?(param = nil) + n = false + if block_given? + my_each { |b| n = true if yield(b) } + elsif param.nil? + my_each { |b| n = true if b } + else + my_each { |b| n = true if param == b } end + n + end + + # my_none method + def my_none?(param = nil) + n = true + if block_given? + my_each { |b| n = false if yield(b) } + else + n = !my_any?(param) + end + n +end - def my_map_again(myproc) #my_mapa_gain method which takes a proc - self.my_each do |b| - mymapagain.push myproc.call(b) + # my_count method + def my_count(*param) + mycount = 0 + length.times do |c| + if param.empty? + if block_given? + mycount += 1 if yield self[c] + else + mycount = 1 + c end - mymapagain + elsif self[c] == param[0] + mycount += 1 + end end - - def my_map_final myproc = nil #my_map_final method which an either take a proc or a block - mymapfinal = [] - self.my_each do |b| - if myproc == nil - mymapfinal.push yield(b) - else - mymapfinal.push myproc.call(b) - end + mycount + end + + # my_map method + def my_map + return to_enum unless block_given? + + mymap = Array.new(length) + length.times { |q| mymap[q] = yield self[q] } + mymap + end + + def my_inject(prev = UNDEFINED, choice = UNDEFINED) + vol = prev + vol = 0 if prev == UNDEFINED + case choice + + when UNDEFINED + if block_given? + my_each do |b| + vol = yield(vol, b) end - mymapfinal - end - - def my_inject #my_inject method - output = nil - my_each = output ? yield (output, b) : self |0| + vol + elsif prev.is_a?(Symbol) + my_inject do |mem, object| + mem.method(prev).call(object) + end + end + else + if choice.is_a?(Symbol) + vol = prev + my_inject(sum) do |mem, object| + mem.method(choice).call(object) + end + end end - output -end - - def multiply_els #multiply_els method - my_inject {|mult, b | mult + b} - - end -end - - - - - -#Testing for my_each method -#(To test each of these methods, you can take it out of the comment and go ahead with the testing ) - -#arraysofnumbers = [2, 4, 6, 8, 10, 12] -#arraysofnumbers.my_each do |numbers| - # numbers *= 5 - # print "#{numbers}" -#end - -#Testing for my_each_with_index method - -#arraysofnumbers = [2, 4, 6, 8, 10, 12, 20, 50, 19, 25, 30, 40] -#arraysofnumbers.my_each_with_index do |value, index| -#puts "arraysofnumbers index #{index} takes the value of #{value}" -#end - -#Testing for my_select method - -#arraysofnumbers = [2, 4, 6, 8, 10, 12, 20, 50, 19, 25, 30, 50] -#output = arraysofnumbers.my_select do |numbers| numbers % 2 != 0; end -#print output - -#Testing for my_all method - -#arraysofnumbers = [2, 4, 6, 8, 10, 12, 20, 50, 19, 25, 30, 40] -#output = arraysofnumbers.my_all? do |b| b % 2 == 0; end -#print output - -#Testing for my_any method - -#arraysofnumbers = [2, 4, 6, 8, 10, 12, 20, 50, 19, 25, 30, 25] -#output = arraysofnumbers.my_any? do |b| b < 3; end -#print output - -#Testing for my_none method - -#arraysofnumbers = [2, 4, 6, 8, 10, 12, 20, 50, 19, 25, 30, 10] -#output = arraysofnumbers.my_none? do |b| b % 2 == 1; end -#print output - -#Testing for my_count method - -#arraysofnumbers = [2, 5, 8, 10, 20, 15, 25, 15, 8, 4, 6] -#arraysofnumbers = [5, 8, 10, 15, 15, 8, 4, 6, 8, 2, 12, 7, 8, 10] -#output = arraysofnumbers.my_count -#output = arraysofnumbers.my_count (10) -#output = arraysofnumbers () do |numbers| numbers % 2 == 1; end -#output = arraysofnumbers (5) do |numbers|; end -#print output - -#Testing for my_map method - -#arraysofnumbers = [2, 4, 6, 8, 10, 12, 20, 50, 19, 25, 30, 20] -#output = arraysofumbers.my_map do |numbers| numbers * 2; end -#print output - -#Testing for my_map_again method (that takes a proc) - -#arraysofnumbers = [2, 4, 6, 8, 10, 12, 20, 50, 19, 25, 30, 10, 10] -#myproc = Proc.new do |numbers| numbers * 2; end -#output = arraysofnumbers.my_map_again(myproc) -#print output - -#Testing for my_map_final(3) (that takes either a proc or a block) - -#arraysofnumbers = [2, 4, 6, 8, 10, 12, 20, 50, 19, 25, 35, 30] -#myproc = Proc.new do |numbers| numbers * 2; end -#output = arraysofnumbers.my_map_final do |numbers| numbers * 3; end -#print output - -#Testing for my_inject method - -#def multiply_els(arraysofnumbers) -#arraysofnumbers.my_inject(1) do |total, numbers|total * numbers; end -#end -#arraysofnumbers = [1, 4, 5, 3, 2] -#puts multiply_els(arraysofnumbers) - + end + # multiply_els method + def multiply_els(param) + param.my_inject(1) { |c, d| c * d } + end +end diff --git a/README.md b/README.md index f83871f..08a61a9 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,91 @@ -# Project Descriptioon: +# Name of Project: -Advanced Building Blocks - Enumerable Methods Using Ruby Language. +Enumerable Methods + +# Table of contents: + +1. About The Project +2. Built With +3. Getting Started With The Project +4. Contributing +5. License +6. Contact/Contributors + i. Link To Project On Github +7. What Was Learnt During The Project +8. Acknowledgements + +# About The Project: + +Enumerable is a module in Ruby that provides many methods that can help with traversal, transforming, sorting, and filtering. Any class that can implement the #each method can use Enumerable methods, which will then yield each item in the collection to a block. + +It can also be said that "Enumerable" is actually a "module", which means it is just a bunch of methods packaged together that can (and do) get "mixed in", or included, with other classes like Array and Hash. It's designed to provide useful functionality to classes representing collections of objects. + +# Built With: + +This Enumerable method project was built using the Ruby language. + +# Getting Started With The Project: + +To get started, here below are the steps that needs to be taken in order to achieve the required result from the project: + +1. Create a script file to house your methods and run it in IRB to test them later. +2. Add your new methods onto the existing Enumerable module. Ruby makes this easy for you because any class or module can be added to without trouble … just do something like: + + module Enumerable + def my_each + # your code here + end + end + +1. Create #my_each, a method that is identical to #each but (obviously) does not use #each. You’ll need to remember the yield statement. Make sure it returns the same thing as #each as well. +2. Create #my_each_with_index in the same way. +3. Create #my_select in the same way, though you may use #my_each in your definition (but not #each). +4. Create #my_all? (continue as above) +5. Create #my_any? +6. Create #my_none? +7. Create #my_count +8. Create #my_map +9. Create #my_inject +10. Test your #my_inject by creating a method called #multiply_els which multiplies all the elements of the array together by using #my_inject, e.g. multiply_els([2,4,5]) #=> 40 +11. Modify your #my_map method to take a proc instead. +12. Modify your #my_map method to take either a proc or a block. It won’t be necessary to apply both a proc and a block in the same #my_map call since you could get the same effect by chaining together one #my_map call with the block and one with the proc. This approach is also clearer, since the user doesn’t have to remember whether the proc or block will be run first. So if both a proc and a block are given, only execute the proc. + +# Contributing: + +In this project, your contributions towards helping in improving this project is woild be well accomodated. With that, the project will get better rating and give programmers at any level the ability learn, be inspired and create better content. + +After you are done with your contributions, you can: + +i. Fork The project. +ii. Create your feature branch using git checkout -b feature/anyfeature(for example) +iii. Commit your changes following git commit -m 'Name it as it pleases you', when you are done, +iv. Push to the branch you have created using git push origin feature/anyfeature and finally +v. Open a pull request. + +# License: + +Distributed under the MIT Licence. See Licence for more informaton # Contributor(s): - -Kingsley McSimon Ogbonna https://github.com/KingsleyMcSimon @KingsleyMcSimon -# Link to the project on Github: +[Kingsley McSimon Ogbonna](https://github.com/KingsleyMcSimon) + +# Link To The Project On Github: + +[Enumerable-Methods](https://github.com/KingsleyMcSimon/Enumerable-Methods) + +# What Was Learnt During The Project: + +I learnt from this project that modules like Enumerable are the ultimate in DRY (Don't Repeat Yourself) code. I also understood that Ruby programmers don't have to write all those methods as mentioned above many different times - they just write them once, package them up as Enumerables and tell Array and Hash to include them. + +# Acknowledgements: + +[Medium - The Enumerable Module](https://medium.com/yello-offline/ruby-the-enumerable-module-under-the-hood-some-caveats-f640ce39a07d) + +[Best ReadMe Template](https://github.com/othneildrew/Best-README-Template) -https://github.com/KingsleyMcSimon/Enumerable-Methods +[The Odin Project - Advanced Building Blocks](https://www.theodinproject.com/courses/ruby-programming/lessons/advanced-building-blocks) +[Vikings - The Enumerable Module ](https://www.vikingcodeschool.com/falling-in-love-with-ruby/the-enumerable-module) +To as many that supported and guided me towards this project, my regards to them all. diff --git a/spec/new_spec.rb b/spec/new_spec.rb new file mode 100644 index 0000000..e69de29 diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..251aa51 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,100 @@ +# This file was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = "doc" + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end