Intro
This is a fun project to extract pokemon data from csv using Ruby.
What we learn
In this project we’ll learn
- How to load and work with CSV in Ruby
- How to filter array data
Requirement
- Ruby
- pokemon.csv download
Problem
As we see in the image below,
I want to choose grass-type pokemon with has attack in medium level, no more than 100 and no less than 90 attack attribute.
Solution
To solve the problem, let’s create some experiment using irb console.
Filter a row
- Import CSV standard library by run
require "csv"
. - Load CSV data and store in a variable,
pokemons = CSV.read("pokemon.csv")
- Read data on row 1 by using,
pokemens[1]
- There are two columns that mark the type of Pokemon, 2 and 3. So we should check these columns.
pokemons[1][2] == "Grass" || pokemons[1][3] == "Grass"
- Then we check column 6 from the table to get attack data, convert to integer, and check the range value.
pokemons[1][6].to_i.between?(90,100)
- Put together in a method
|
|
Filter all rows
Then, to get all rows that meet the criteria we create loop
|
|
The result can be seen by running p selected_pokemons
Use blocks
From the function we defined earlier
|
|
and turn it into a block
|
|
It’s a different syntax, but it looks a lot like a function. There are some operations on arrays that can take it and do stuff with it (https://ruby-doc.org/core-3.1.0/Array.html). In our case, we use select
method
|
|
Additional Featurs
The final code will be
|
|
with additional feature i.e. sort_by
.
Full list of method can be shown here https://ruby-doc.org/core-3.1.0/Array.html
Additional Resources
There are lot of resources about block in Ruby: